<template>
  <div class="my-customer-wrap common-set-wrap">
    <div class="right-content">
      <div class="right-box" :style="{ 'min-height': bgHeight }">
        <div class="apps-content flex" :style="{ 'min-height': bgHeight }">
          <div class="apps-content-right">
            <div class="overstore-body">
              <div class="overstore-tip">
                <div role="alert" class="el-alert el-alert--info flex flex-align-start ">
                  <i class="el-alert__icon el-icon-warning font-12 color-2f54eb"></i>
                  <div class="el-alert__content">
                    <span class="el-alert__title color-303133 font-13">仅展示近一年数据，数据截取时间：{{ dateStart | timeStampToYmd2 }} 至 {{ dateEnd | timeStampToYmd2 }}</span>
                  </div>
                </div>
                <el-popover placement="bottom-start" width="550" trigger="click" popper-class="salesleads-popover">
                  <div class="tips-content">只统计通过GIC创建的群发，不包含在企业微信创建的群发及门店创建的群发</div>
                  <div slot="reference" role="tips" class="tips flex flex-align-center">
                    <i class="el-icon-warning-outline font-14 color-2f54eb"></i>
                    <div class="el-alert__content">查看指标说明</div>
                  </div>
                </el-popover>
              </div>
              <div class="table-condition-search flex flex-space-between m-t-20">
                <div class="table-condition-left">
                  <el-input placeholder="请输入门店名称" prefix-icon="el-icon-search" v-model="pageParams.storeName" class="w-260" @change="reFetch" clearable> </el-input>
                  <gic-select-group :brandId="brandId" class="m-l-10" :width="213" :selectData="pageParams.storeGroup" @checkGroupIds="checkGroupIds"> </gic-select-group>
                  <el-date-picker class="m-l-10" prefix-icon="el-icon-time" :picker-options="pickerOptions" v-model="pageParams.date" @change="changeDate" :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 v-if="$getButtonLimit($buttonCode.exportStoreList)" :limit-code="$buttonCode.exportStoreList" :loading="loadingBtn" type="primary" @click="exportExcel">导出</el-button>
                </div>
              </div>
              <div class="m-t-20">
                <el-table v-loading="loading" :key="tableRefresh" class="select-table" ref="multipleTable" :data="tableData" tooltip-effect="dark" style="width: 100%;" @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="scope">{{ scope ? ' ' : ' ' }}</template>
                  </el-table-column>
                  <el-table-column label="门店名称" show-overflow-tooltip>
                    <template slot-scope="scope"
                      >{{ scope.row.storeName || '--' }}
                      <p style="color:#909399">{{ scope.row.storeCode }}</p>
                    </template>
                  </el-table-column>
                  <el-table-column prop="" label="门店分组">
                    <template slot-scope="scope">{{ scope.row.storeGroupName || '--' }}</template>
                  </el-table-column>
                  <el-table-column prop="" label="任务总数">
                    <template slot-scope="scope">{{ scope.row.taskCnt || '--' }}</template>
                  </el-table-column>
                  <el-table-column prop="" label="已完成">
                    <template slot-scope="scope">{{ scope.row.cplTaskCnt || '--' }}</template>
                  </el-table-column>
                  <el-table-column prop="" label="完成率">
                    <template slot-scope="scope">{{ (scope.row.completionRate * 100).toFixed(2) + '%' || '--' }}</template>
                  </el-table-column>
                  <el-table-column prop="" label="待完成">
                    <template slot-scope="scope">{{ scope.row.waitFinishCount || '--' }}</template>
                  </el-table-column>
                  <el-table-column prop="" label="逾期中/逾期失效">
                    <template slot-scope="scope">{{ scope.row.ovincplTaskCnt || '--' }}/{{ scope.row.invalidCount || '--' }}</template>
                  </el-table-column>
                  <el-table-column prop="" label="操作" width="150" v-if="$getButtonLimit($buttonCode.checkStoreList)">
                    <template slot-scope="scope">
                      <el-button v-if="$getButtonLimit($buttonCode.checkStoreList)" :limit-code="$buttonCode.checkStoreList" type="text" @click="showDetail(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">
                  <el-pagination background :page-sizes="[20, 40, 60, 80]" :page-size="pageParams.pageSize" :current-page="pageParams.pageNum" layout="total, sizes, prev, pager, next, jumper" :total="total" style="text-align:right;" @current-change="handleCurrentChange" @size-change="handleSizeChange"> </el-pagination>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import showMsg from '@/common/js/showmsg';
import gicSelectGroup from '@/components/common/gic-select-group.vue';
import navCrumb from '@/components/nav/nav.vue';
import { getRequest, postExcel } from '@/api/api';
import errMsg from '@/common/js/error';
import { _debounce } from '@/common/js/public';
export default {
  name: 'storeList',
  props: {
    brandId: {
      type: String,
      default() {
        return '';
      }
    }
  },
  data() {
    return {
      selectRadio: 2, // 选择当页/选择全部
      tableRefresh: false,
      multipleSelection: [],
      bgHeight: window.screen.availHeight - 298 + 'px',
      dateStart: new Date().getTime() - 3600 * 1000 * 24 * 365,
      dateEnd: new Date(),
      loading: false,
      // 面包屑参数
      navpath: [
        {
          name: '首页',
          path: '/index'
        },
        {
          name: '营销任务',
          path: '/trafficTaskSet'
        },
        {
          name: '话务任务-话务任务设置',
          path: ''
        }
      ],
      pageParams: {
        pageNum: 1,
        pageSize: 20,
        storeGroup: [],
        storeName: '',
        date: this.$store.state.salesDate
      },
      // 分页参数
      total: 0,
      tableData: [
        // {
        //   storeId: '', // 门店id
        //   storeName: '', // 门店名称
        //   taskCnt: '', // 任务总数
        //   cplTaskCnt: '', // 任务完成数
        //   completionRate: '', // 任务完成率
        //   waitFinishCount: '', // 待完成数
        //   itincplTaskCnt: '', // 未逾期任务未完成数
        //   ovincplTaskCnt: '', // 逾期任务未完成数
        // }
      ],
      pickerOptions: {
        disabledDate: time => {
          const end = new Date();
          return time.getTime() < end.getTime() - 3600 * 1000 * 24 * 365 || time.getTime() > end.getTime() - 3600 * 1000 * 24;
        }
      },
      loadingBtn: false
    };
  },
  computed: {},
  methods: {
    /**
     * 表格选择
     */
    handleSelectionChange(val) {
      this.multipleSelection = val;
      val.length ? '' : (this.selectRadio = 2);
    },
    /**
     * 显示选择本页/全部
     */
    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();
      }
    },
    /**
     * 导出
     */
    exportExcel() {
      if (!this.multipleSelection.length) {
        showMsg.showmsg('请选择门店', 'warning');
        return false;
      }
      this.loadingBtn = true;
      let url = '/haoban-task-manage-web/market/clue/export/store-view';
      const { pageNum, pageSize, storeName } = this.pageParams;
      let para = {
        pageNum,
        pageSize,
        storeName,
        taskType: 2,
        selectType: this.selectRadio,
        selectIdList: this.selectRadio == 1 ? '' : this.multipleSelection.map(ele => ele.storeId).join(','), // 门店分组,数组
        enterpriseId: sessionStorage.getItem('userInfoBrandId'),
        qywxEnterpriseId: JSON.parse(localStorage.getItem('userInfos')).wxEnterpriseId,
        startTime: this.pageParams.date[0],
        endTime: this.pageParams.date[1]
      };
      if (this.pageParams.storeGroup) {
        let storeGroups = [];
        this.pageParams.storeGroup.forEach(ele => {
          storeGroups.push(ele.storeGroupId);
        });
        para.storeGroupIds = storeGroups.join(',') || '';
      }
      let fileName = this.pageParams.date.length ? `群发任务-门店视图_${para.startTime}至${para.endTime}.xls` : `群发任务-门店视图.xls`;
      if (this.$route.query.hasOwnProperty('ecmPlanName')) {
        para = { ...para, ...this.$route.query };
        url = '/haoban-task-manage-web/market/clue/export/plan-view-task-store-detail';
        fileName = this.pageParams.date.length ? `群发任务-计划视图-任务门店详情_${para.startTime}至${para.endTime}.xls` : `群发任务-计划视图-任务门店详情.xls`;
      }
      postExcel(url, para)
        .then(res => {
          this.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 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) {
          this.$message.error({
            duration: 1000,
            message: error.message
          });
        })
        .finally(() => {
          this.loadingBtn = false;
        });
    },
    checkGroupIds: function(nodes) {
      const that = this;
      that.pageParams.storeGroup = nodes;
      that.reFetch();
    },
    /**
     * 路由跳转
     */
    changeRoute(path) {
      this.$router.push(path);
    },
    /**
     * 筛选
     */
    reFetch: _debounce(function(e, value) {
      const that = this;
      that.pageParams.pageNum = 1;
      that.getTableList();
    }, 500),
    /**
     *  日期
     */
    changeDate(e) {
      if (!e) {
        this.pageParams.date = [];
        this.$store.dispatch('changeSales', []);
      } else {
        this.$store.dispatch('changeSales', e);
      }
      this.pageParams.pageNum = 1;
      this.getTableList();
    },
    /**
     * 分页---页码变化
     *  @param {Number} val
     */
    handleSizeChange(val) {
      const that = this;
      that.pageParams.pageNum = 1;
      that.pageParams.pageSize = val;
      that.getTableList();
    },

    /**
     * 分页---当前页变化
     *  @param {Number} val
     */
    handleCurrentChange(val) {
      const that = this;
      that.pageParams.pageNum = val;
      that.getTableList();
    },
    /**
     * 获取列表数据
     */
    getTableList(val) {
      const that = this;
      that.loading = true;
      let para = {
        ...that.pageParams,
        enterpriseId: sessionStorage.getItem('userInfoBrandId'),
        qywxEnterpriseId: JSON.parse(localStorage.getItem('userInfos')).wxEnterpriseId,
        taskType: 2
      };
      if (that.pageParams.storeGroup) {
        let storeGroups = [];
        that.pageParams.storeGroup.forEach(ele => {
          storeGroups.push(ele.storeGroupId);
        });
        delete para.storeGroup;
        para.storeGroupIds = storeGroups.join(',') || '';
      }
      if (para.date) {
        para.startTime = para.date[0];
        para.endTime = para.date[1];
        delete para.date;
      }
      if (that.$route.query.ecmPlanId) {
        para.ecmPlanId = that.$route.query.ecmPlanId;
      }
      getRequest('/haoban-task-manage-web/market/clue/web/store-list', para)
        .then(res => {
          that.loading = false;
          let resData = res.data;
          if (resData.errorCode == 1) {
            that.tableData = resData.result.list || [];
            that.total = resData.result.pageInfo ? resData.result.pageInfo.total : 0;
          } else {
            errMsg.errorMsg(resData);
          }
        })
        .catch(function(error) {
          that.loading = false;
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    showDetail(item) {
      if (this.$route.query.ecmPlanId) {
        this.$router.push(`grStoreDetail/${item.storeId}?tab=2&ecmPlanId=${this.$route.query.ecmPlanId}&ecmPlanName=${this.$route.query.ecmPlanName}`);
      } else {
        this.$router.push(`grStoreDetail/${item.storeId}`);
      }
    }
  },
  watch: {
    brandId(newV) {
      this.getTableList();
    },
    $route(to, from) {
      if (!this.$route.query.ecmPlanId) {
        this.getTableList();
      }
    }
  },
  mounted() {
    this.getTableList();
    if (this.$route.query.ecmPlanId) {
      this.$emit('showTab', '212', '2121');
    } else {
      this.$emit('showTab', '211');
    }
    document.documentElement.style.backgroundColor = '#f0f2f5';
  },
  destroyed() {
    document.documentElement.style.backgroundColor = '#fff';
  },
  components: {
    navCrumb,
    gicSelectGroup
  }
};
</script>
<style type="text/scss" lang="scss" scoped>
.bg-82C5FF {
  background: #82c5ff;
}
.color-508CEE {
  color: #508cee;
}
.color-FF585C {
  color: #ff585c;
}
.line-h-18 {
  line-height: 18px;
}
.tooltip-text {
  width: 100%;
  white-space: pre-wrap;
  word-break: break-all;
}
.w-260 {
  width: 260px;
}
.el-alert--info {
  background: rgba(240, 245, 255, 1);
  border-radius: 2px;
  border: 1px solid rgba(133, 165, 255, 1);
  -webkit-box-align: flex-start;
  -webkit-align-items: flex-start;
  -ms-flex-align: flex-start;
  align-items: flex-start;
  .el-alert__icon {
    font-size: 12px;
  }
}
.my-customer-wrap {
  height: 100%;
}
.right-content {
  /*width: 100%;*/
  padding: 0;
  min-height: calc(100% - 160px);
  .right-box {
    background: #fff;
    min-height: 500px;
    padding: 0px;
    .apps-content {
      .apps-content-right {
        width: 100%;
        padding: 20px;
        background: #fff;
        .overstore-body {
          background: #fff;
          .overstore-tip {
            display: flex;
            justify-content: flex-start;
            align-items: center;
            .el-alert--info {
              align-items: center;
              width: 444px;
              height: 32px;
              padding: 0 0 0 17px;
              margin-right: 17px;
              .el-alert__content {
                padding-left: 0;
              }
            }
            .tips {
              cursor: pointer;
              .el-alert__content {
                font-size: 13px;
                font-weight: 400;
                color: #2f54eb;
                line-height: 1;
              }
            }
          }
        }
        .daily-set-wrap {
          height: 100%;
          background: #fff;
        }
        .app-detail-wrap {
          height: 100%;
          background: #fff;
        }
        .common-set-wrap {
          height: 100%;
          background: #fff;
        }
      }
    }
  }
}
</style>
