<template>
  <div class="agency-diamond-flow">
    <div class="container">
      <div class="region-box">
        <el-radio-group v-model="region">
          <el-radio
            v-for="(item, index) in userAreaRegion"
            :key="index"
            :label="item.value"
            >{{ item.name }}</el-radio
          >
        </el-radio-group>
      </div>
      <div class="handle-box">
        <el-form
          ref="searchForm"
          :model="searchForm"
          :rules="searchRule"
          label-width="90px"
          :disabled="tableLoading"
        >
          <div class="search-line">
            <el-form-item label="公会ID" prop="agencyId">
              <el-input
                v-model.trim="searchForm.agencyId"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
            <el-form-item label="公会长ID" prop="agencyOwnerId">
              <el-input
                v-model.trim="searchForm.agencyOwnerId"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
            <el-form-item label="周期" prop="dateCycle">
              <el-select placeholder="请选择" v-model="searchForm.dateCycle">
                <el-option
                  v-for="(item, i) in dateCycleList"
                  :key="i"
                  :label="item.startDateStr + '~' + item.endDateStr"
                  :value="item.dateCycle"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label-width="40px">
              <el-button type="primary" @click="handSearch">搜索</el-button>
              <el-button plain @click="resetSearchForm">重置搜索</el-button>
            </el-form-item>
          </div>
        </el-form>
        <el-button type="primary" class="exportBtn" @click="confirmExport2Excel"
          >导出</el-button
        >
      </div>
      <div class="table">
        <el-table
          :data="tableData"
          border
          v-loading="tableLoading"
          @header-click="headerCopy"
          style="width: 100%"
        >
          <!-- <el-table-column align="center" prop="region" label="区服">
                        <template v-slot="scope">
                            {{ regionType(scope.row.region) }}
                        </template>
                    </el-table-column> -->
          <el-table-column align="center" prop="agencyId" label="公会ID">
          </el-table-column>
          <el-table-column align="center" prop="agencyName" label="公会名称">
          </el-table-column>
          <el-table-column
            align="center"
            prop="hallMemberCount"
            label="主播人数"
          >
          </el-table-column>
          <!-- <el-table-column align="center" prop="agencyAbbr" label="公会国家"> </el-table-column> -->
          <el-table-column align="center" prop="agencyErbanNo" label="公会长ID">
          </el-table-column>
          <el-table-column align="center" prop="energyValue" label="总钻石流水">
            <template v-slot="scope">
              {{ scope.row.energyValue.toLocaleString() }}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="salaryRate"
            label="公会长薪资比例"
          >
            <template v-slot="scope">
              {{ scope.row.salaryRate ? scope.row.salaryRate + "%" : "0%" }}
            </template>
          </el-table-column>
          <el-table-column align="center" prop="hallSalary" label="公会长薪资">
          </el-table-column>
        </el-table>
      </div>
      <table-pagination
        :pageParams="pageParams"
        :pageTotal="pageTotal"
        :page-sizes="[10, 20, 100, 200]"
        @handleSizeChange="handleSizeChange"
        @handlePageChange="handlePageChange"
      ></table-pagination>
    </div>
  </div>
</template>

<script lang=js>
import { getDateCycleList, getAgencyDiamondFlow, agencyDiamondFlowExport } from '@/api/relAgency/relAgency.js';
import TablePagination from '@/components/common/TablePagination';
import { formatDate, formatDateYMD } from '@/utils/relDate';
// @ts-ignore
import { ElMessage } from "element-plus";
import { ref } from 'vue'; // 引入 ref
import { ElMessageBox } from 'element-plus'; // 正确引入 ElM
// 混入
// import Mixin from '../../mixin/mixRegion.js';

export default {
    name: "agencyDiamondFlow",
    // mixins: [Mixin],
    components: { TablePagination },
    data() {
        return {
            dateCycleList: [],
            btnLoading: false, // 导出弹出框(dialog)的确认按钮
            tableLoading: false, // 表格是否加载中

            tableData: [], // 接口返回的表格数据
            pageTotal: 0, // 接口返回的表格总条数
            pageParams: {
                pageNo: 1,
                pageSize: 20
            },
            // 搜索表单相关
            searchForm: {
                agencyOwnerId: null,
                agencyId: null,
                dateCycle: null,
                region: null
            },
            searchRule: {
                startTime: [
                    {
                        validator: (rule, value, callback) => {
                            this.$refs['searchForm'].validateField('endTime');
                            callback();
                        },
                        trigger: 'change'
                    }
                ],
                endTime: [
                    {
                        validator: (rule, value, callback) => {
                            const { startTime } = this.searchForm;
                            if (startTime !== null && startTime !== '' && value) {
                                if (value <= startTime) {
                                    callback(new Error('须晚于开始时间'));
                                } else {
                                    callback();
                                }
                            } else {
                                callback();
                            }
                        },
                        trigger: 'change'
                    }
                ]
            }
        };
    },
    created() {
        this.getDateCycleList();
    },
    methods: {
        getDateCycleList() {
            getDateCycleList({ month: 3 }).then((res) => {
                this.dateCycleList = res.data || [];
            });
        },
        getData() {
            this.tableLoading = true;

            let { pageParams, searchForm } = this;
            searchForm = JSON.parse(JSON.stringify(searchForm));
            pageParams = JSON.parse(JSON.stringify(pageParams));
            Object.keys(searchForm).forEach((item) => {
                if (!searchForm[item] || (searchForm[item] !== undefined && searchForm[item] === '')) {
                    delete searchForm[item];
                }
            });
            Object.assign(pageParams, searchForm);

            getAgencyDiamondFlow(pageParams).then((res) => {
                this.tableLoading = false;
                if (res.code == 200) {
                    let data = res.data;
                    this.tableData = data.records;
                    this.pageTotal = data.total;
                }else{
                    ElMessage({
                    showClose: true,
                    message: res.message,
                    type: "error",
                    });
            }
            });
        },
        // 点击搜索
        handSearch() {
            this.$refs['searchForm'].validate((valid) => {
                if (valid) {
                    this.pageParams.pageNo = 1;
                    this.getData();
                }
            });
        },
        // 重置搜索表单
        resetSearchForm() {
            this.$refs['searchForm'].resetFields();
            this.pageParams.pageNo = 1;
            this.getData();
        },
        // 确认导出
        confirmExport2Excel() {
           ElMessageBox.confirm('确定以当前筛选条件导出Excel吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {
                    this.btnLoading = true;
                    let { searchForm } = this;
                    searchForm = JSON.parse(JSON.stringify(searchForm));
                    Object.keys(searchForm).forEach((item) => {
                        if (!searchForm[item] || (searchForm[item] !== undefined && searchForm[item] === '')) {
                            delete searchForm[item];
                        }
                    });
                    Object.assign(searchForm, { pageSize: 10000, pageNo: 1 });

                    agencyDiamondFlowExport(searchForm)
                        .then((res) => {
                            if (res) {
                                this.exportVisible = false;
                                this.btnLoading = false;
                                let time = formatDate(new Date());
                                let alink = document.createElement('a');
                                alink.download = `公会钻石薪资流水统计${time}.xls`;
                                alink.style.display = 'none';
                                const blob = new Blob([res.data]);
                                alink.href = URL.createObjectURL(blob);
                                document.body.appendChild(alink);
                                alink.click();
                                URL.revokeObjectURL(alink.href);
                            }
                        })
                        .catch((err) => {
                            console.error(err); // 打印错误信息
                           ElMessage({
                                showClose: true,
                                message:"导出失败",
                                type: "error",
                            });
                        });
                })
                .catch(() => {
                });
        },
        // 分页导航
        handleSizeChange(val) {
           this.pageParams.pageSize = val;
            this.getData();
        },
        handlePageChange(val) {
          this.pageParams.pageSize = val;
            this.getData();
        },
        headerCopy(column, e) {
            this.$copy(column.label);
        }
    },
    computed: {
        convertTimestamp1() {
            return function (time) {
                let date = new Date(time);
                return formatDateYMD(date);
            };
        },
        convertTimestamp() {
            return function (time) {
                let date = new Date(time);
                return formatDate(date);
            };
        }
    }
};
</script>

<style scope>
.exportBtn {
  margin-bottom: 20px;
}

.container {
  width: 100%;
}
.search-line {
  width: 38%;
}
</style>
