<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form :model="queryParams" inline>

        <el-form-item label="企微主体" prop="corpId">
          <el-select v-model="queryParams.corpId" placeholder="企微主体" size="small" @change="updateCorpId()">
            <el-option
              v-for="dict in myQwCompanyList"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="所属部门" prop="deptId">
          <treeselect style="width:220px" v-model="queryParams.deptId" :options="deptOptions" :show-count="true" placeholder="请选择所属部门" />
        </el-form-item>

        <el-form-item label="员工">
          <el-input
            v-model="queryParams.companyUserName"
            placeholder="输入员工姓名"
            clearable
          />
        </el-form-item>
        <el-form-item label="企微客服">
          <el-input
            v-model="queryParams.qwUserName"
            placeholder="输入企微客服"
            clearable
          />
        </el-form-item>

        <el-form-item label="统计日期">
          <el-date-picker
            v-model="queryParams.statDate"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            :loading="exportLoading"
            @click="handleExport"
          >导出</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table :data="tableData" border v-loading="loading">
      <el-table-column prop="corpName" label="企微客服" align="center" />
      <el-table-column
        label="部门"
        align="center"
        :show-overflow-tooltip="true"
        :formatter="formatDeptName"
      />

      <el-table-column prop="nickName" label="员工" align="center" />
      <el-table-column prop="externalTotal" label="总客户数" align="center" />
      <el-table-column prop="totalCustomers" label="已注册客户数" align="center" />
      <el-table-column prop="downloadCount" label="下载APP数" align="center" />
      <el-table-column prop="notDownloadCount" label="未下载APP数" align="center" />
      <el-table-column prop="downloadRate" label="下载率" align="center">
        <template slot-scope="scope">
          {{ (scope.row.downloadRate * 100).toFixed(2) }}%
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import {getSalesAppDownloadStats, exportSalesAppDownloadStats} from '../../../api/qw/externalContact';
import {listDept, treeselect,listDeptExcludeChild} from "@/api/company/companyDept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {getMyQwCompanyList} from "@/api/qw/user";
export default {
  name: 'AppDownloadStatistics',
  components: {Treeselect},
  data() {
    return {
      queryParams: {
        corpId: null,
        pageNum: 1,
        pageSize: 10,
        departmentName: "",
        companyUserName: "",
        qwUserName: "",
        myQwCompanyList: [],
        statDate: this.formatDate(new Date())
      },
      tableData: [],
      total: 0,
      loading: false,
      deptOptions: undefined,
      deptList:[],
      deptMap: {},
      // 导出遮罩层
      exportLoading: false,
    }
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    this.getList();
    this.getTreeselect();
    getMyQwCompanyList().then(response => {
      this.myQwCompanyList = response.data;
      if (this.myQwCompanyList != null) {
        this.queryParams.corpId = this.myQwCompanyList[0].dictValue;
        this.getList();
      }
    });
  },
  methods: {
    // 格式化日期为 YYYY-MM-DD
    formatDate(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },

    // 获取统计数据 - 使用假数据
    getList() {
      this.loading = true;
      getSalesAppDownloadStats(this.queryParams).then(response => {
        this.tableData = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then((response) => {
        this.deptOptions = response.data;
        this.deptMap = this.flattenDeptTree(this.deptOptions);
      });
    },
    // 查询处理
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    // 重置查询
    handleReset() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 20,
        departmentName: undefined,
        employeeName: undefined,
        statDate: this.formatDate(new Date())
      }
      this.getList()
    },
    flattenDeptTree(tree, map = {}) {
      tree.forEach(node => {
        map[node.id] = node.label
        if (node.children) {
          this.flattenDeptTree(node.children, map)
        }
      })
      return map
    },
    formatDeptName(row) {
      const id = Number(row.deptId)
      return this.deptMap[id] || ''
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有销售统计项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.exportLoading = true;
        return exportSalesAppDownloadStats(queryParams);
      }).then(response => {
        this.download(response.msg);
        this.exportLoading = false;
      }).catch(() => {});
    }

  }
}
</script>
