<template>
  <div class="statistics">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="服务目标数据统计" name="plan" v-if="showInfo">
        <avue-crud
          ref="crud"
          :option="option"
          v-model="form"
          :page.sync="page"
          :table-loading="tableLoading"
          :data="tableData"
          @size-change="sizeChange"
          @current-change="currentChange"
          @refresh-change="refreshChange"
        />
      </el-tab-pane>
      <el-tab-pane label="服务管理数据统计" name="pkg" v-if="showInfo">
        <avue-crud
          ref="crud"
          :option="option"
          v-model="form"
          :page.sync="page"
          :table-loading="tableLoading"
          :data="tableData"
          @size-change="sizeChange"
          @current-change="currentChange"
          @refresh-change="refreshChange"
        />
      </el-tab-pane>
      <el-tab-pane label="服务商评分" name="provider" v-if="showInfo">
        <avue-crud
          ref="crud"
          :option="option"
          v-model="form"
          :page.sync="page"
          :table-loading="tableLoading"
          :data="tableData"
          @size-change="sizeChange"
          @current-change="currentChange"
          @refresh-change="refreshChange"
        >
          <template slot="products" slot-scope="scope">
            <div>
              <div v-for="(item, index) in scope.row.products" class="products">{{ index + 1 }}、{{ item }}</div>
            </div>
          </template>
        </avue-crud>
      </el-tab-pane>
      <el-tab-pane label="服务商与业务员数据统计页面" name="providerTree" v-if="showInfo">
        <avue-crud
          ref="crud"
          :option="option"
          v-model="form"
          :page.sync="page"
          :table-loading="tableLoading"
          :data="tableData"
          @size-change="sizeChange"
          @current-change="currentChange"
          @refresh-change="refreshChange"
        >
          <template slot="menu" slot-scope="scope">
            <el-button type="text" size="small" @click="salespersonStatisticsFn(scope.row, scope.index)">业务员数据统计 </el-button>
          </template></avue-crud
        >
      </el-tab-pane>
      <el-tab-pane label="风险控制数据统计" name="supervision">
        <avue-crud
          ref="crud"
          :option="option"
          v-model="form"
          :page.sync="page"
          :table-loading="tableLoading"
          :data="tableData"
          @size-change="sizeChange"
          @current-change="currentChange"
          @refresh-change="refreshChange"
        />
      </el-tab-pane>
    </el-tabs>
    <el-dialog title="业务员数据统计" :visible.sync="dialogVisible" width="80%" center>
      <el-table
        :data="userList"
        max-height="650"
        border
        style="width: 100%"
        :header-cell-style="{'text-align': 'center', background: '#fafafa'}"
        :cell-style="{'text-align': 'center'}"
      >
        <el-table-column prop="userName" label="接包对象"> </el-table-column>
        <el-table-column prop="phone" label="手机号" width="150"> </el-table-column>
        <el-table-column prop="userPkgCount" label="下发执行包数量"> </el-table-column>
        <el-table-column prop="userPkgScoreTotal" label="下发执行包积分总计"> </el-table-column>
        <el-table-column prop="taskScoreTotal" label="完成分值"> </el-table-column>
        <el-table-column prop="taskScoreRate" width="100" label="完成分值百分比（%）（积分）"> </el-table-column>
        <el-table-column prop="passedScore" label="审核通过积分值"> </el-table-column>
        <el-table-column prop="passedRate" width="100" label="服务商管理员提交百分比（%）"> </el-table-column>
        <el-table-column prop="userTaskCount" label="服务商代表提交任务数量"> </el-table-column>
        <el-table-column prop="passedCount" label="服务商管理员提交任务数量"> </el-table-column>
        <el-table-column prop="passedCountRate" label="审核通过率（%）（次数）"> </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {statPlanTreeApi, statPkgTreeApi, statProviderApi, statProviderTreeApi, supervisionDataApi} from '@/api/statistics/index.js';
import {formatWithThousandSeparator, planTableOption, pkgTableOption, provideTableOption, providerTreeTableOption, supervisionTableOption} from '@/const/crud/statistics/index.js';
import {getAreaTreeApi} from '@/api/areaTree';
import {mapGetters} from 'vuex';
export default {
  data() {
    return {
      activeName: 'plan',
      tableLoading: false,
      option: planTableOption,
      tableData: [],
      form: {},
      userList: [],
      dialogVisible: false,
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20 // 每页显示多少条,
      },
      areaTree: [],
      showInfo: true
    };
  },
  computed: {
    ...mapGetters(['userInfo'])
  },

  created() {
    const roles = this.userInfo.roles;
    const rolesArr = [49, 51, 52, 57, 58, 61];
    let flag = roles.some(item => rolesArr.includes(item));
    if (flag) {
      this.activeName = 'supervision';
      this.option = supervisionTableOption;
      this.showInfo = false;
    }
    this.getList();
    this.getAreaTree();
  },
  methods: {
    async getAreaTree() {
      const res = await getAreaTreeApi();
      if (res.data.code === 0) {
        this.areaTree = res.data.data;
      }
    },
    handleClick() {
      this.tableData = [];
      this.page = {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20 // 每页显示多少条,
      };
      switch (this.activeName) {
        case 'plan':
          this.option = planTableOption;
          break;
        case 'pkg':
          this.option = pkgTableOption;
          break;
        case 'provider':
          this.option = provideTableOption;
          break;
        case 'providerTree':
          this.option = providerTreeTableOption;
          break;
        case 'supervision':
          this.option = supervisionTableOption;
          break;
        default:
          break;
      }
      this.getList();
    },
    setIndex(list, fIndex) {
      list.forEach((item, index) => {
        if (!fIndex) {
          item.index = index + 1;
        } else {
          item.index = fIndex + '-' + (index + 1);
        }
        if (item.children) {
          this.setIndex(item.children, item.index);
        }
      });
      return list;
    },
    async getList() {
      this.tableLoading = true;
      const obj = {
        current: this.page.currentPage,
        size: this.page.pageSize
      };
      try {
        let res;
        switch (this.activeName) {
          case 'plan':
            res = await statPlanTreeApi(obj);
            this.processPlanData(res.data.data.records);
            break;
          case 'pkg':
            res = await statPkgTreeApi(obj);
            this.processPkgData(res.data.data.records);
            break;
          case 'provider':
            res = await statProviderApi(obj);
            this.processProviderData(res.data.data.records);
            break;
          case 'providerTree':
            res = await statProviderTreeApi(obj);
            break;
          case 'supervision':
            res = await supervisionDataApi(obj);
            break;
          default:
            res = {data: {data: {records: [], total: 0}}};
            break;
        }
        const records = this.setIndex(res.data.data.records);
        this.tableData = records;
        this.page.total = res.data.data.total;
      } catch (error) {
        console.error('Error fetching data:', error);
        this.$message.error('数据加载失败，请稍后重试');
      } finally {
        this.tableLoading = false;
      }
    },

    /**
     * 处理计划数据
     * @param {Array} records
     */
    processPlanData(records) {
      records.forEach(item => {
        if (!item.children && item.parentId !== 0) {
          item.distRate = '---';
          return;
        }
        if (item.planType === 'ANN') {
          item.distRate = '---';
          return;
        }
        if (item.children && item.children.length > 0) {
          const totalScore = item.children.reduce((total, child) => {
            child.distRate = '---';
            return total + (child.planScore || 0);
          }, 0);
          const percentage = item.planScore ? (totalScore / item.planScore) * 100 : 0;
          item.distRate = `${percentage.toFixed(2)}%`;
        } else {
          item.distRate = '0%';
        }
      });
    },

    /**
     * 处理包数据
     * @param {Array} records
     */
    processPkgData(records) {
      const calculateCompletedScore = node => {
        if (!node.children || node.children.length === 0) {
          return node.completedScore || 0;
        }
        const totalCompletedScore = node.children.reduce((total, child) => total + calculateCompletedScore(child), 0);
        node.completedScore = totalCompletedScore;
        if (node.distScore && node.completedScore) {
          node.completedRate = `${((node.completedScore / node.distScore) * 100).toFixed(2)}%`;
        }
        return totalCompletedScore;
      };
      records.forEach(item => calculateCompletedScore(item));
    },

    /**
     * 处理供应商数据
     * @param {Array} records
     */
    processProviderData(records) {
      records.forEach(item => {
        item.children = item.packages || [];

        item.children.forEach(child => {
          if (child.redemptionNotices && child.redemptionNotices.length > 0) {
            const totalRedemption = child.redemptionNotices.reduce((total, notice) => total + (notice.currentRedemptionTotal || 0), 0);
            child.serviceMark = totalRedemption / child.redemptionNotices.length || '';
          } else {
            child.serviceMark = '';
          }
        });

        const validChildren = item.children.filter(child => child.redemptionNotices && child.redemptionNotices.length > 0);
        const totalServiceMark = validChildren.reduce((total, child) => total + (child.serviceMark || 0), 0);

        item.serviceMark = validChildren.length ? totalServiceMark / validChildren.length : '';
      });
    },

    // page修改
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.getList(this.page);
    },
    currentChange(current) {
      this.page.currentPage = current;
      this.getList(this.page);
    },
    refreshChange() {
      this.getList(this.page);
    },
    salespersonStatisticsFn(row) {
      this.userList = JSON.parse(JSON.stringify(row.userList));

      console.log('row.userList', row.userList);

      this.userList.forEach(item => {
        if (item.passedScore && item.taskScoreTotal) {
          let percentage = (item.passedScore / item.taskScoreTotal) * 100;
          item.passedRate = `${percentage.toFixed(2)}%`;
        }
        if (item.taskScoreTotal && item.userPkgScoreTotal) {
          let percentage = (item.taskScoreTotal / item.userPkgScoreTotal) * 100;
          item.taskScoreRate = `${percentage.toFixed(2)}%`;
        }
        if (item.passedCount && item.taskPkgCount) {
          let percentage = (item.passedCount / item.taskPkgCount) * 100;
          item.passedCountRate = `${percentage.toFixed(2)}%`;
        }

        item.userPkgScoreTotal = item.userPkgScoreTotal ? formatWithThousandSeparator(Number(item.userPkgScoreTotal)) : 0;
        item.taskScoreTotal = item.taskScoreTotal ? formatWithThousandSeparator(Number(item.taskScoreTotal)) : 0;
        item.passedScore = item.passedScore ? formatWithThousandSeparator(Number(item.passedScore)) : 0;
      });

      this.dialogVisible = true;
    },

    filterTree(tree, areaCodes) {
      const areaCodeSet = new Set(areaCodes);
      function filterNode(node) {
        if (!areaCodeSet.has(node.areaCode)) {
          return null;
        }
        const filteredChildren = (node.children || []).map(filterNode).filter(child => child !== null);

        return {
          ...node,
          children: filteredChildren
        };
      }
      // 对整棵树进行递归过滤
      return tree.map(filterNode).filter(node => node !== null);
    },

    getTreeData(areaCodes) {
      if (areaCodes) {
        const areaCodesArr = areaCodes.map(item => String(item));
        const tree = JSON.parse(JSON.stringify(this.areaTree));
        const filteredTree = this.filterTree(tree, areaCodesArr);
        return filteredTree;
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.statistics {
  margin-top: 20px;
  background: #fff;
  padding: 15px 10px;
  min-height: 300px;
  background-color: #fff;
  border-radius: 10px;
}
.products {
  text-align: left;
}
</style>
