<!--
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2019-03-20 14:36:37
 * @LastEditors: 无尘
 * @LastEditTime: 2020-11-05 15:26:00
 -->
<!--
<taskViewDetail :brandId="brandId" :activeGroupId="activeGroupId"></taskViewDetail>
import taskViewDetail from '@/components/app/taskViewDetail.vue';
-->
<template>
  <div class="daily-set-wrap task-view-detail">
    <div class="daily-set-content border-box">
      <div class="table-condition flex flex-space-between m-b-23">
        <div class="table-condition-left">
          <el-input placeholder="请输入门店名称" maxlength="50" v-model="conditionObj.searchInput" class="w-264" style="width: 264px;" @keyup.native="value => toInput(value, conditionObj.searchInput)"> <i slot="prefix" class="el-input__icon el-icon-search"></i> </el-input>
          <gic-select-group :brandId="brandId" class="m-l-10" :width="213" :selectData="conditionObj.storeGroup" @checkGroupIds="checkGroupIds"> </gic-select-group>
          <el-date-picker class="m-l-10" v-model="conditionObj.dateRange" @change="changeDate" :editable="false" :value-format="'yyyy-MM-dd'" type="daterange" align="right" unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"> </el-date-picker>
        </div>
        <div class="table-condition-right">
          <el-button type="danger" @click="multDel">批量删除</el-button>
          <el-button :loading="loadingBtn" type="primary" @click="beforeExportExcel">导出</el-button>
          <el-tooltip content="导出结果中会员姓名、手机号等敏感信息将进行加密，实现隐私保护" placement="top">
            <i class="el-icon-warning-outline font-14 p-l-6" v-show="enableDownloadCompleteData == 0"></i>
          </el-tooltip>
        </div>
      </div>
      <el-table class="select-table" ref="multipleTable" :key="tableRefresh" v-loading="loading" :data="tableData" tooltip-effect="dark" :style="{ width: '100%', minHeight: tableH }" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="45" :class-name="selectRadio == 1 ? 'cell-disabled' : 'font-size-zero'"> </el-table-column>
        <el-table-column width="25">
          <template #header>
            <el-dropdown style="line-height: 10px; padding: 0; margin-left: -15px; transform: translateY(4px); -webkit-transform: translateY(4px);" placement="bottom-start">
              <span class="el-dropdown-link"><i class="iconfont-hb3 icongengduo"></i> </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item> <el-checkbox v-model="selectRadio" :true-label="0" :false-label="2" @change="handleCommand">选择当页</el-checkbox></el-dropdown-item>
                <el-dropdown-item> <el-checkbox v-model="selectRadio" :true-label="1" :false-label="2" @change="handleCommand">选择全部</el-checkbox></el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
          <template slot-scope="{ $index }"><p :key="$index"></p></template>
        </el-table-column>
        <el-table-column label="门店分组" width="120" show-overflow-tooltip>
          <template slot-scope="scope">{{ scope.row.storeGroupName }}</template>
        </el-table-column>
        <el-table-column label="门店名称" width="120" show-overflow-tooltip>
          <template slot-scope="scope">
            <div style="width: 100%;white-space:nowrap;overflow:hidden;text-overflow: ellipsis;">{{ scope.row.storeName }}</div>
            <p style="color:#909399">{{ scope.row.storeCode }}</p>
          </template>
        </el-table-column>
        <el-table-column prop="" label="任务总数">
          <template slot-scope="scope">{{ scope.row.taskCount }}</template>
        </el-table-column>
        <el-table-column prop="" label="已完成(含放弃)" show-overflow-tooltip>
          <template slot-scope="scope">{{ scope.row.completedCount }}</template>
        </el-table-column>
        <el-table-column prop="" label="完成率(含放弃)" show-overflow-tooltip>
          <template slot-scope="scope">{{ scope.row.completedRate }}</template>
        </el-table-column>
        <el-table-column prop="" label="待完成" show-overflow-tooltip>
          <template slot-scope="scope">{{ scope.row.noCompletedCount }}</template>
        </el-table-column>
        <el-table-column prop="" label="逾期中" show-overflow-tooltip>
          <template slot-scope="scope">{{ scope.row.overdueCount }}</template>
        </el-table-column>
        <el-table-column label="逾期失效">
          <template slot-scope="scope">{{ scope.row.invalidCount }}</template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text" @click="toDetail(scope.$index, scope.row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block common-wrap__page text-right m-t-24" v-if="tableData.length != 0">
        <dm-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[20, 40, 60, 80]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"> </dm-pagination>
      </div>
    </div>
    <export-dialog :dialogVisible="exportDialog" @export="exportExcel" @update:dialogVisible="changeExportDialog" />
    <multiple-del :showDialog="showDialog" :detailFlag="false" @hideDialog="hideDialog" :showTip="true"> </multiple-del>
  </div>
</template>
<script>
import exportDialog from '@/components/common/export-dialog.vue';
import gicSelectGroup from '@/components/common/gic-select-group.vue';
import multipleDel from '@/components/app/cloudDaily/multiple-del.vue';
import { getRequest, postRequest, postExcel } from '@/api/api';
import { _debounce } from '@/common/js/public';
import showMsg from '@/common/js/showmsg';
import errMsg from '@/common/js/error';
export default {
  name: 'reviewed',
  props: {
    brandId: {
      type: String,
      default() {
        return '';
      }
    },
    activeGroupId: {
      type: String,
      default() {
        return '';
      }
    },
    enableDownloadCompleteData: {
      type: [Number, String],
      default() {
        return 0;
      }
    }
  },
  data() {
    return {
      tableH: window.screen.availHeight - 464 - 126,
      activeTab: '1',
      activeBrand: this.brandId, // 商户(品牌) id
      activeGroup: this.activeGroupId, // 商户(品牌) groupId

      activeId: '2',
      showDialog: false,
      // 条件
      conditionObj: {
        searchInput: '',
        storeGroup: [],
        storeType: '',
        dateRange: this.$store.state.salesDate
      },
      loading: false,
      selectRadio: 2, // 选择当页/选择全部
      tableData: [
        // {
        //   storeName: '2016-05-03',
        //   taskCount: '王小虎',
        //   completed: '10',
        //   completionRate: '10',
        //   unCompleted: '10',
        //   overdue: '1',
        //   taskId: '123',
        //   storeId: '123456',
        //   address: '上海市普陀区金沙江路 1518 弄'
        // }
      ],
      multipleSelection: [],
      // 分页参数
      currentPage: 1,
      pageSize: 20,
      total: 0,
      loadingBtn: false,
      tableRefresh: false,
      exportDialog: false
    };
  },
  computed: {},
  methods: {
    beforeExportExcel() {
      if (!this.multipleSelection.length) {
        showMsg.showmsg('请选择门店', 'warning');
        return false;
      }
      if (this.enableDownloadCompleteData == 1) {
        this.exportDialog = true;
      } else {
        this.exportExcel(0);
      }
    },
    changeExportDialog() {
      this.exportDialog = false;
      this.multipleSelection = [];
      this.$refs.multipleTable.clearSelection();
    },
    /**
     * 导出
     */
    exportExcel(type) {
      const that = this;
      if (!that.multipleSelection.length) {
        showMsg.showmsg('请选择门店', 'warning');
        return false;
      }
      let storeGroups = [];
      that.conditionObj.storeGroup.forEach(ele => {
        storeGroups.push(ele.storeGroupId);
      });
      that.loadingBtn = true;

      let para = {
        search: that.conditionObj.searchInput || '', // 搜索字段
        storeGroupIds: storeGroups.join(',') || '', // 门店分组,数组
        startDate: that.conditionObj.dateRange[0] || '',
        endDate: that.conditionObj.dateRange[1] || '',
        ecmId: that.$route.query.ecmId,
        ecmPlanName: this.$route.query.ecmName,
        storeIds: that.selectRadio == 1 ? '' : that.multipleSelection.map(ele => ele.storeId).join(','), // 门店分组,数组
        gicEnterpriseId: that.activeBrand, // 品牌 id
        selectType: that.selectRadio == 2 && that.multipleSelection.length ? 0 : this.selectRadio,
        dataType: type
      };
      postExcel('/haoban-app-tel-task-three-web/task/export-task-view-store-list', para)
        .then(res => {
          that.loadingBtn = false;
          if (!res.data) {
            errMsg.errorMsg('暂无数据');
            return false;
          }
          // let resData = res.data;
          const blob = new Blob([res.data], {
            type: 'application/vnd.ms-excel'
          });
          const fileName = `话务任务视图详情门店报表.xls`;
          const elink = document.createElement('a');
          elink.download = fileName;
          elink.style.display = 'none';
          elink.href = URL.createObjectURL(blob);
          document.body.appendChild(elink);
          elink.click();
          URL.revokeObjectURL(elink.href); // 释放URL 对象
          document.body.removeChild(elink);
          // errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.loadingBtn = false;
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    /**
     * 选择门店分组
     */
    checkGroupIds: function(nodes) {
      const that = this;
      that.conditionObj.storeGroup = nodes;
      that.currentPage = 1;
      that.getTableList();
    },
    /**
     * 改变视图
     */
    changeTable(e) {
      const that = this;
      that.currentPage = 1;
      that.getTableList();
    },
    /**
     * 显示选择本页/全部
     */
    handleCommand(command) {
      this.selectRadio = command;
      this.tableRefresh = !this.tableRefresh;
      if (command == 1 || command == 0) {
        this.$nextTick(() => {
          this.$refs.multipleTable.toggleAllSelection();
        });
      } else if (command == 2) {
        this.$refs.multipleTable.clearSelection();
      }
    },
    /**
     * 返回 的 brandId
     */
    setSelectTab(item) {
      let that = this;
      that.activeTab = item.tabId;
    },

    /**
     * 输入
     */
    toInput: _debounce(function(e, value) {
      let that = this;
      that.currentPage = 1;
      that.getTableList();
    }, 500),

    /**
     * 门店类型
     */
    changeStoreType() {
      let that = this;
      that.currentPage = 1;
      that.getTableList();
    },

    /**
     * 日期
     */
    changeDate(e) {
      let that = this;
      if (!e) {
        this.$store.dispatch('changeSales', []);
      } else {
        this.$store.dispatch('changeSales', e);
      }
      that.currentPage = 1;
      that.getTableList();
    },

    /**
     * 表格选择
     */
    handleSelectionChange(val) {
      this.multipleSelection = val;
      val.length ? '' : (this.selectRadio = 2);
    },

    /**
     * 删除选的部门
     */
    delDepart(index, item) {
      let that = this;
      item.splice(index, 1);
      that.currentPage = 1;
      that.getTableList();
    },

    /**
     * 批量删除
     */
    multDel() {
      let that = this;
      if (!that.multipleSelection.length) {
        that.$message.error({
          duration: 1000,
          message: '请选择删除项'
        });
        return false;
      }
      that.showDialog = true;
    },

    /**
     * 批量删除---弹窗关闭
     */
    hideDialog(obj) {
      let that = this;
      that.showDialog = false;
      if (!Object.keys(obj).length) {
        return false;
      }
      that.postMultDel(obj);
    },

    postMultDel(obj) {
      let that = this;
      let storeGroups = [];
      that.conditionObj.storeGroup.forEach(ele => {
        storeGroups.push(ele.storeGroupId);
      });
      let para = {
        search: that.conditionObj.searchInput || '', // 搜索字段
        storeGroupIds: storeGroups.join(',') || '', // 门店分组,数组
        storeIds: that.selectRadio == 1 ? '' : that.multipleSelection.map(ele => ele.storeId).join(','), // 门店分组,数组
        storeType: that.conditionObj.storeType || '', //门店类型
        startDate: that.conditionObj.dateRange[0] || '',
        endDate: that.conditionObj.dateRange[1] || '',
        enterpriseId: that.activeBrand, // 品牌 id
        delTaskStatus: obj.delOptFlag, // 0:仅删除逾期任务，1:删除所有待完成任务
        reason: obj.reason, // 备注
        isAll: that.selectRadio, // 1：当页，1：所有
        ecmId: that.$route.query.ecmId
        // taskType: 1 //0不良评价，1话务任务
      };
      postRequest('/haoban-app-tel-task-three-web/task/batch-del-store-task-list', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            showMsg.showmsg('删除成功', 'success');
            that.getTableList();
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    /**
     * 分页---页码变化
     *  @param {Number} val
     */
    handleSizeChange(val) {
      const that = this;
      that.currentPage = 1;
      that.pageSize = val;
      that.getTableList(this.selectRadio);
    },

    /**
     * 分页---当前页变化
     *  @param {Number} val
     */
    handleCurrentChange(val) {
      const that = this;
      that.currentPage = val;
      // let fullPath = that.$route.fullPath;
      that.getTableList(this.selectRadio);
    },

    /**
     * 弹窗显示事件
     */
    showDialogLayer(type, selData) {
      const that = this;
      that.selectType = type;
      that.changed = type;
      that.defaultStoreList = selData;
      that.storeTreeSet = {
        dialogVisible: true,
        isSingle: false,
        isSelectPerson: false
      };
    },

    /**
     * 处理已选部门
     */
    handleSelectedList(group) {
      let that = this;
      // type:	1:员工,2:部门,3:门店;
      that.conditionObj.storeGroup = group;
      that.getTableList();
    },

    /**
     * 查看详情
     */
    toDetail(index, row) {
      let that = this;
      that.$router.push(`taskDetail?storeId=${row.storeId}&ecmId=${that.$route.query.ecmId}`);
    },

    /**
     * 获取列表数据
     */
    getTableList(val) {
      const that = this;
      that.loading = true;
      let storeGroups = [];
      that.conditionObj.storeGroup.forEach(ele => {
        storeGroups.push(ele.storeGroupId);
      });
      let para = {
        ecmId: that.$route.query.ecmId,
        search: that.conditionObj.searchInput || '', // 搜索字段
        storeGroupIds: storeGroups.join(',') || '', // 门店分组,分组
        storeType: that.conditionObj.storeType || '', //门店类型
        startDate: that.conditionObj.dateRange[0] || '',
        endDate: that.conditionObj.dateRange[1] || '',
        pageNum: that.currentPage, // 当前页
        pageSize: that.pageSize, // 一页显示个数
        enterpriseId: that.activeBrand
        // taskType: 1 //0不良评价，1话务任务
      };
      getRequest('/haoban-app-tel-task-three-web/task/store-task-list', para)
        .then(res => {
          let resData = res.data;
          that.loading = false;
          if (resData.errorCode == 1) {
            that.tableData = resData.result.list || [];
            that.total = resData.result.pageInfo.total;
            if (val == 1) {
              this.$nextTick(() => {
                this.$refs.multipleTable.toggleAllSelection();
              });
            } else {
              this.selectRadio = 2;
            }
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.loading = false;
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    }
  },
  watch: {
    brandId: function(newData, oldData) {
      let that = this;
      if (!!newData) {
        that.activeBrand = newData;
        that.getTableList();
      }
      this.multipleSelection = [];
    },
    activeGroupId: function(newData, oldData) {
      let that = this;
      if (!!newData) {
        that.activeGroup = newData;
      }
    }
  },
  mounted() {
    const that = this;
    that.$emit('showTab', '122', '1221');
    document.documentElement.style.backgroundColor = '#f0f2f5';
    that.activeBrand = that.brandId;
    if (!!that.brandId) {
      that.$nextTick(() => {
        that.getTableList();
      });
    }
  },
  destroyed() {
    document.documentElement.style.backgroundColor = '#fff';
  },
  components: {
    gicSelectGroup,
    multipleDel,
    exportDialog
  }
};
</script>
<style type="text/scss" lang="scss" scoped>
.color-c0c4cc {
  display: inline-block;
  line-height: 34px;
  padding-left: 10px;
  color: #c0c4cc;
}
.table-condition {
  // min-width: 1200px;
}
.daily-set-wrap {
  height: 100%;
  .daily-set-content {
    padding: 16px;
    .table-condition-left {
      font-size: 0;
    }
  }
  .depart-item-content {
    width: 213px;
    height: 32px;
    overflow: hidden;
    white-space: nowrap;
    border-radius: 4px;
    border: 1px solid #dcdfe6;
    cursor: pointer;
  }
  .item-cell-select {
    >>> .el-select__tags {
      white-space: nowrap;
      overflow: hidden;
    }
  }
  .depart-cell {
    position: relative;
    margin: 0 24px 24px 0;
    .el-icon-circle-close {
      position: absolute;
      top: -10px;
      right: -10px;
      font-size: 16px;
      color: #808995;
      cursor: pointer;
    }
  }
}
</style>
