<template>
  <div class="my-customer-wrap common-set-wrap">
    <div class="right-content">
      <div class="right-box">
        <div class="apps-content flex">
          <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>
              </div>
              <div class="table-condition-search flex flex-space-between m-t-20">
                <div class="table-condition-left">
                  <span style="font-size:14px;margin-right：-4px;">创建时间：</span>
                  <el-date-picker 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>
                  <el-select class="w-103 m-l-10" v-model="pageParams.finishOverStatus" slot="prepend" placeholder="所有完成情况" @change="reFetch">
                    <el-option :label="item.text" :value="item.id" v-for="item in filterOpts" :key="'filter' + item.id"></el-option>
                  </el-select>
                  <el-input placeholder="请输入任务标题" prefix-icon="el-icon-search" v-model="pageParams.taskTitle" class="w-260 m-l-10" @change="reFetch" clearable> </el-input>
                </div>
                <div class="table-condition-right">
                  <el-button v-if="$getButtonLimit($buttonCode.exportStoreDetail)" :limit-code="$buttonCode.exportStoreDetail" :loading="loadingBtn" type="primary" @click="exportExcel">导出</el-button>
                </div>
              </div>
              <div class="m-t-20">
                <el-table v-loading="loading" class="select-table" ref="multipleTable" :data="tableData" tooltip-effect="dark" style="width: 100%;" :key="tableRefresh" @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 min-width="120">
                    <template slot-scope="scope">{{ scope.row.taskTitle || '--' }}</template>
                  </el-table-column>
                  <el-table-column prop="" label="导购" min-width="200">
                    <template slot-scope="scope">
                      <div class="flex flex-align-center personal-info">
                        <el-image :src="scope.row.executeClerkClerkImgUrl || headDefault" fit="cover"></el-image>
                        <div>
                          <p class="color-303133 line-20">{{ scope.row.executeClerkName || '--' }}</p>
                          <p class="color-909399 line-20">{{ scope.row.executeClerkPhoneNum || '--' }}</p>
                        </div>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="" label="创建时间" min-width="122">
                    <template slot-scope="scope">
                      <div class="color-606266 line-20">{{ scope.row.createTime | timeStampToYmd }}</div>
                      <div class="color-606266 line-20">{{ scope.row.createTime | timeStampToHms }}</div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="" label="完成期限" min-width="122">
                    <template slot-scope="scope">
                      <div class="color-606266 line-20">{{ scope.row.overdueTime | timeStampToYmd }}</div>
                      <div class="color-606266 line-20">{{ scope.row.overdueTime | timeStampToHms }}</div>
                    </template>
                  </el-table-column>
                  <el-table-column label="逾期情况/逾期失效" min-width="140">
                    <template slot-scope="scope"><span class="point" :style="'background:' + overdueStyle[scope.row.overdueStatus] + ';'"></span>{{ scope.row.overdueStatus === 1 ? '已逾期' : scope.row.overdueStatus === 2 ? '未逾期' : '' }}/{{ scope.row.invalidStatus | formatInvalidStatus }}</template>
                  </el-table-column>
                  <el-table-column label="完成情况" min-width="90">
                    <template slot-scope="scope"><span v-if="scope.row.taskStatus" class="point" :style="'background:' + taskStyle[scope.row.taskStatus] + ';'"></span>{{ scope.row.taskStatus === 1 ? '未完成' : scope.row.taskStatus === 2 ? '已完成' : '' }}</template>
                  </el-table-column>
                  <el-table-column label="完成详情" min-width="280">
                    <template slot-scope="scope"> 待发送：{{ scope.row.waitSendCount }}，已发送：{{ scope.row.successCount }}，发送失败：{{ scope.row.failCount }} </template>
                  </el-table-column>
                  <el-table-column label="操作" width="150" v-if="$getButtonLimit($buttonCode.checkStoreDetail) || $getButtonLimit($buttonCode.previewStoreDetail)">
                    <template slot-scope="scope">
                      <el-button v-if="$getButtonLimit($buttonCode.checkStoreDetail)" :limit-code="$buttonCode.checkStoreDetail" type="text" @click="showDetail(scope.row)">详情</el-button>
                      <el-button v-if="$getButtonLimit($buttonCode.previewStoreDetail)" :limit-code="$buttonCode.previewStoreDetail" type="text" @click="showPreview(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 @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageParams.pageNum" :page-sizes="[20, 40, 60, 80]" :page-size="pageParams.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-pagination>
                </div>
              </div>
              <salesleads-taskinfo :item="finishDetail" :date="pageParams.date" :storeId="$route.params.id" :ecmPlanName="$route.query.ecmPlanName" v-if="finishDetailShow" @close="close"></salesleads-taskinfo>
              <detail-preview ref="detailPreview" :previewData="previewData" v-model="previewVisible" @closePreview="closePreview"></detail-preview>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- <vue-gic-footer></vue-gic-footer> -->
  </div>
</template>
<script>
import salesleadsTaskinfo from '@/components/review/salesleads-task-info.vue';
import headDefault from '@/assets/head_default.jpg';
import { getRequest, postRequest, postExcel } from '@/api/api';
import errMsg from '@/common/js/error';
import showMsg from '@/common/js/showmsg';
import { _debounce } from '@/common/js/public';
import detailPreview from '@/components/review/salesleads-detail-preview.vue';
export default {
  name: 'storeDetail',
  props: {
    brandId: {
      type: String,
      default() {
        return '';
      }
    }
  },
  data() {
    return {
      selectRadio: 2, // 选择当页/选择全部
      tableRefresh: false,
      multipleSelection: [],
      headDefault,
      loading: false,
      dateStart: new Date().getTime() - 3600 * 1000 * 24 * 365,
      dateEnd: new Date(),
      pageParams: {
        storeId: this.$route.params.id,
        finishOverStatus: '0',
        taskType: 2,
        pageNum: 1,
        pageSize: 20,
        date: this.$store.state.salesDate
      },
      filterOpts: [],
      overdueOpts: [
        { label: '已逾期', value: 1 },
        { label: '未逾期', value: 2 }
      ],
      // 分页参数
      total: 0,
      tableData: [
        // {
        //   taskId: '', // 任务id
        //   taskTitle: '', // 任务标题
        //   executeClerkId: '', // 指派导购id
        //   executeClerkName: '', // 指派导购名字
        //   executeClerkPhoneNum: '', // 指派导购手机号
        //   executeClerkClerkImgUrl: null, // 指派导购头像
        //   createTime: null, // 创建时间
        //   overdueTime: null, // 逾期时间
        //   overdueStatus: null, // 逾期状态(1:逾期,2:未逾期)
        //   taskStatus: null // 完成情况(1:未完成,2:完成)
        //   taskDetail: // 待发送：1，已发送：2，发送失败：1
        // }
      ],
      overdueStyle: ['none', '#F5222D', '#2F54EB'],
      taskStyle: ['none', '#F5222D', '#33AF4A'],
      finishDetailShow: false,
      finishDetail: {},
      previewData: {},
      previewVisible: false,
      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(type) {
      if (!this.multipleSelection.length) {
        showMsg.showmsg('请选择任务', 'warning');
        return false;
      }
      this.loadingBtn = true;
      let url = '/haoban-task-manage-web/market/clue/export/store-view-task-detail';
      const { finishOverStatus, taskType, pageNum, pageSize, date } = this.pageParams;
      let para = {
        enterpriseId: this.brandId,
        dataType: 1,
        finishOverStatus,
        taskType,
        pageNum,
        pageSize,
        // startTime: this.pageParams.date[0],
        // endTime: this.pageParams.date[1],
        selectType: this.selectRadio,
        selectIdList: this.selectRadio == 1 ? '' : this.multipleSelection.map(ele => ele.taskId).join(','), // 门店分组,数组
        storeId: this.$route.params.id
      };
      if (Array.isArray(date) && date.length === 2) {
        para.startTime = `${date[0]} 00:00:00`;
        para.endTime = `${date[1]} 23:59:59`;
      }
      let fileName = this.pageParams.date.length ? `群发任务-门店视图-任务详情_${para.startTime}至${para.endTime}.xls` : `群发任务-门店视图-任务详情.xls`;
      if (this.$route.query.hasOwnProperty('ecmPlanName')) {
        para.ecmPlanName = this.$route.query.ecmPlanName;
        url = '/haoban-task-manage-web/market/clue/export/plan-view-task-store-task-detail';
        para.ecmPlanId = this.$route.query.ecmPlanId;
        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;
        });
    },
    /**
     * 路由跳转
     */
    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: this.brandId,
        storeId: that.$route.params.id
      };
      if (Array.isArray(para.date) && para.date.length === 2) {
        para.startTime = `${para.date[0]} 00:00:00`;
        para.endTime = `${para.date[1]} 23:59:59`;
        delete para.date;
      }

      if (this.$route.query.ecmPlanId) {
        para.ecmPlanId = this.$route.query.ecmPlanId;
      }
      getRequest('/haoban-task-manage-web/market/clue/web/send-task-info-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
          });
        });
    },
    getFilterOpts() {
      const that = this;
      getRequest('/haoban-task-manage-web/market/clue/web/query', {})
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1 && resData.result) {
            that.filterOpts = resData.result;
            that.pageParams.finishOverStatus = '0';
          } else {
            errMsg.errorMsg(resData);
          }
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    showDetail(item) {
      const that = this;
      that.finishDetail = {
        enterpriseId: this.brandId,
        taskId: item.taskId
      };
      this.finishDetailShow = true;
    },
    close() {
      this.finishDetailShow = false;
      this.finishDetail = {};
    },
    showPreview(item) {
      const that = this;
      let para = {
        enterpriseId: this.brandId,
        taskId: item.taskId
      };
      postRequest('/haoban-task-manage-web/market/clue/web/send-task-preview', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            that.previewData = resData.result;
            that.previewVisible = true;
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    closePreview() {
      const that = this;
      that.previewData = {};
    }
  },
  watch: {
    brandId(newV) {
      this.getTableList();
    }
  },
  mounted() {
    const that = this;
    that.getFilterOpts();
    that.$nextTick(() => {
      that.getTableList();
    });
  },
  components: {
    salesleadsTaskinfo,
    detailPreview
  }
};
</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: 291px;
              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;
        }
      }
    }
  }
}
.personal-info {
  .el-image {
    width: 40px;
    height: 40px;
    margin-right: 10px;
  }
}
</style>
