<!--
 * @Descripttion: 查看门店
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2020-11-09 10:39:37
 * @LastEditors: 无尘
 * @LastEditTime: 2020-12-01 10:41:10
-->
<template>
  <div class="common-app-right">

    <div class="list-content" v-loading="loading">
      <common-alert-tip :tip-content="tipContent"></common-alert-tip>
      <div class="content-search m-t-20">
        <div class="content-first">
          <el-input
            v-model.trim="search.search"
            placeholder="请输入名称/code"
            prefix-icon="el-icon-search"
            @keydown.enter.native="searchChange"
            clearable
            @change="searchChange">
          </el-input>

          <el-select class="w-171" v-model="search.performanceSubType" placeholder="全部指标类型" @change="searchChange" clearable>
            <el-option :label="`${[ '业绩', '新增会员' ][activeName - 1]}指标日权重`" value="1"></el-option>
            <el-option :label="`${[ '业绩', '新增会员' ][activeName - 1]}指标日指标`" value="2"></el-option>
          </el-select>

          <el-select v-model="search.flag" placeholder="全部状态" clearable @change="searchChange">
            <el-option label="日指标已完善" value="0"></el-option>
            <el-option label="日指标未完善" value="1"></el-option>
            <el-option label="导购指标已完善" value="2"></el-option>
            <el-option label="导购指标未完善" value="3"></el-option>
          </el-select>

          <el-select v-model="search.storeEdit" placeholder="全部编辑权限" clearable @change="searchChange">
            <el-option label="店长可编辑" value="1"></el-option>
            <el-option label="店长不可编辑" value="0"></el-option>
          </el-select>

          <el-select v-model="search.storeType" style="width: 106px;margin-right: -1px" @change="storeChange">
            <el-option label="门店分组" value="1"></el-option>
            <el-option label="门店标签" value="2"></el-option>
          </el-select>

          <gic-select-group-mult
            v-if="search.storeType === '1'"
            width="148px"
            :brand-id="brandId"
            @checkGroupIds="checkGroupIds">
          </gic-select-group-mult>

          <gic-select-tag
            v-if="search.storeType === '2'"
            width="148px"
            :brand-id="brandId"
            @returnTags="checkGroupIds">
          </gic-select-tag>

        </div>

        <el-select v-model="multValue" :disabled="search.performanceSubType == 2" placeholder="批量操作" @change="batchOperation" clearable>
          <el-option label="完善日指标" :value="1"></el-option>
        </el-select>
      </div>

      <!-- <div class="content-data">
        <div>
          <span class="color2">总业绩指标：¥  </span>
          <span class="color1">100,000</span>
        </div>
      </div> -->

      <el-table
        :data="tableData"
        style="width: 100%"
        ref="multipleTable"
        @selection-change="handleSelectionChange">

        <el-table-column type="selection" width="55"></el-table-column>

        <el-table-column label="指标类型" show-overflow-tooltip>
          <template slot-scope="{row}">
            {{ ['业绩', '新增会员'][row.performanceType - 1] }}
          </template>
        </el-table-column>
        <el-table-column label="门店名称" show-overflow-tooltip>
          <template slot-scope="{row}">
            {{ row.storeName || '--' }}
          </template>
        </el-table-column>
        <el-table-column label="业绩指标" show-overflow-tooltip>
          <template slot="header">
            {{ [ '业绩', '新增会员' ][activeName - 1] }}指标
          </template>
          <template slot-scope="{row}">
            {{ row.performanceValue ? `￥${row.performanceValue}` : '--' }}
          </template>
        </el-table-column>
        <el-table-column label="日指标" show-overflow-tooltip>
          <template slot-scope="{row}">
            <div :class="{
              'state-point': true,
              'state-point-success': row.dayFlag == 1,
              'state-point-default': row.dayFlag != 1,
              }">
              {{ [ '未完善', '已完善' ][row.dayFlag || 0] }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="导购指标" show-overflow-tooltip>
          <template slot-scope="{row}">
            <div :class="{
              'state-point': true,
              'state-point-success': row.clerkFlag == 1,
              'state-point-default': row.clerkFlag != 1,
              }">
              {{ [ '未完善', '已完善' ][row.clerkFlag || 0] }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="更新时间" show-overflow-tooltip>
          <template slot-scope="{row}">
            <div style="line-height:18px">
              {{ row.updateTime | formatDate('ymd') }} <br /> {{ row.updateTime | formatDate('hms') }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="提交人" show-overflow-tooltip>
          <template slot-scope="{row}">
            {{ row.submitStaffName || '--' }}
          </template>
        </el-table-column>

        <el-table-column prop="date" label="操作" width="220">
          <template slot-scope="{row}">
            <el-button
              type="text"
              :disabled="row.dayFlag != 1"
              @click="$router.push({
                path: '/perfect-sale-target',
                query: {
                  applicationId,
                  tab: haoban.performanceType,
                  performanceYm: haoban.performanceYm,
                  performanceSubType: row.performanceSubType,
                  performanceType: row.performanceType,
                  storeInfoId: row.storeInfoId,
                  storeName: row.storeName,
                  performanceValue: row.performanceValue,
                  flag: row.clerkFlag == 1
                }
              })">
              {{ [ '完善', '查看' ][row.clerkFlag || 0] }}导购指标
            </el-button>
            <el-button
              type="text"
              @click="$router.push({
                path: '/perfect-day-target',
                query: {
                  applicationId,
                  tab: haoban.performanceType,
                  performanceYm: haoban.performanceYm,
                  performanceSubType: row.performanceSubType,
                  performanceType: row.performanceType,
                  storeInfoId: row.storeInfoId,
                  storeName: row.storeName,
                  performanceValue: row.performanceValue,
                  flag: row.dayFlag == 1
                }
              })">
              {{ [ '完善', '查看' ][row.dayFlag || 0] }}日指标
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <dm-pagination
        v-if="tableData.length"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.pageNum"
        :page-sizes="[20, 40, 60, 80]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next"
        :total="page.total"
        style="text-align:right">
      </dm-pagination>
    </div>
  </div>
</template>

<script>
import commonAlertTip from '@/components/common/common-alert-tip.vue';
import gicSelectGroupMult from '@/components/common/gic-select-group-mult.vue';
import gicSelectTag from '@/components/common/gic-select-tag.vue';
import fetch from '@/api/target-manage-app.js';
const { getStorePerformanceDetail } = fetch;
export default {
  name: 'TargetStore',
  components: { gicSelectGroupMult, gicSelectTag, commonAlertTip },
  props: {
    brandId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      activeName: '',
      applicationId: '',
      haoban: {},
      tipContent: '仅支持批量设置日权重，暂无法批量设置日指标',
      search: {
        search: '',
        performanceSubType: '',
        storeEdit: '', // 1店长可编辑，0店长不可编辑
        storeType: '1', // 1门店分组，2门店标签
        storeParam: '',
        flag: '',
      },

      multValue: '', // 批量完善日指标
      multipleSelection: [],
      tableData: [],
      loading: false,
      page: {
        pageNum: 1,
        pageSize: 20,
        total: 0
      },
      flagList: [
        { dayFlag: 1 },
        { dayFlag: 0 },
        { clerkFlag: 1 },
        { clerkFlag: 0 },
      ]
    };
  },
  created() {
    const { tab, applicationId, performanceYm } = this.$route.query;
    this.activeName = tab || '0';
    this.applicationId = applicationId;
    const { staffId, wxEnterpriseId } = JSON.parse(localStorage.getItem('haoBanUser'));
    this.haoban = { staffId, wxEnterpriseId, performanceType: tab, performanceYm };

    // 修改面包屑
    let bread = [ { name: '指标管理', path: '/target-list' }, { name: '查看门店' } ];
    bread[0].path += `?applicationId=${applicationId}&tab=${tab}`;
    this.$emit('change-nav', bread);
  },

  mounted() {
    const that = this;
    that.$emit('showTab', '/target-list');
    this.getData();
  },

  methods: {
    getData() {
      this.loading = true;
      const { storeType, storeParam, flag } = this.search;
      let params = {
        ...this.search,
        ...this.haoban,
        ...this.page,
        enterpriseId: this.brandId,
        storeType: storeParam ? storeType : '',
      };
      if (flag) params = { ...params, ...this.flagList[flag] }; // 状态

      getStorePerformanceDetail(params, { headers: { sign: this.brandId } })
        .then(res => {
          const { result, totalCount } = res.result || {};
          this.tableData = result || [];
          this.page.total = totalCount;
        })
        .catch(() => this.tableData = [])
        .finally(() => this.loading = false);
    },
    // 批量完善日指标
    batchOperation(val) {
      const that = this;
      if (!that.search.performanceSubType) return that.$message.warning('请选择指标类型');
      if (!that.multipleSelection.length) {
        that.$message.warning('请选择门店');
        that.multValue = '';
        return false;
      }
      switch (val) {
        case 1:
          that.$store.dispatch('saveStoreInfo', that.multipleSelection);
          return this.$router.push(`perfect-day-target?applicationId=${this.applicationId}&tab=${that.haoban.performanceType}&performanceYm=${that.haoban.performanceYm}&performanceSubType=${that.search.performanceSubType}&performanceType=${that.haoban.performanceType}&storeInfoId=&storeName=&performanceValue=0&flag=false&multOpt=1`);
        case 3:
          if (!this.multipleSelection || !this.multipleSelection.length) return this.$message.warning('请选择指标门店');
          // 判断是否一致
          let edit = this.multipleSelection[0].storeEdit;
          let bool = this.multipleSelection.some(item => item.storeEdit !== edit);
          if (bool) return this.$message.warning('选择的指标门店的 编辑权限 必须一致');

          localStorage.setItem('targetStoreInfoIds', JSON.stringify(this.multipleSelection));
          return this.$router.push({ path: '/edit-store-quota', query: { applicationId: this.applicationId, edit: '3', year: this.search.performanceYear, storeEdit: edit } });
        default:
          break;
      }
    },

    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    handleClick({ name }) {
      console.log(name);
    },

    handleSizeChange(val) {
      this.page.pageSize = val;
      this.page.pageNum = 1;
      this.getData();
    },

    handleCurrentChange(val) {
      this.page.pageNum = val;
      this.getData();
    },
    // 筛选条件变更
    searchChange() {
      this.handleCurrentChange(1);
    },
    // 门店分组change
    checkGroupIds(nodes) {
      console.log(nodes);
      this.search.storeParam = nodes.map(item => item[this.search.storeType === '1' ? 'storeGroupId' : 'storeTagId']).join(',');
      this.searchChange();
    },
    storeChange() {
      this.search.storeParam = '';
      this.searchChange();
    }
  },
  filters: {
    formatDate(val, format) {
      if(!val) return '--';
      val = new Date(val);
      let y = val.getFullYear();
      let m = (val.getMonth() + 1).toString().padStart(2, '0');
      let d = val.getDate().toString().padStart(2, '0');
      let h = val.getHours().toString().padStart(2, '0');
      let mm = val.getMinutes().toString().padStart(2, '0');
      let s = val.getSeconds().toString().padStart(2, '0');
      if(format == 'ymd') {
        return `${y}-${m}-${d}`;
      } else if(format == 'hms') {
        return `${h}:${mm}:${s}`;
      }
      return `${y}-${m}-${d}\xa0\xa0\xa0${h}:${mm}:${s}`;
    }
  },
  watch: {
    brandId(val) {
      val && this.getData();
    }
  },
};
</script>

<style lang='less' scoped>
.list-content {
  .el-input {
    width: 180px;
    margin-right: 10px;
  }
  .el-select {
    width: 148px;
    margin-right: 10px;
  }
  .el-date-picker {
    margin-right: 10px;
  }
  .w-171 {
    width: 171px;
  }
}
// .el-select .el-input.is-focus .el-input__inner {
//   z-index: 2;
// }
.content-search {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}
.content-first {
  display: flex;
  // align-content: center;
}
.content-data {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}
.color1 {
  color: #303133;
  font-size: 16px;
  padding-right: 15px;
  font-weight: 500;
}
.color2 {
  position: relative;
  color: #606266;
  font-size: 14px;
  font-weight: 400;
  &:not(:first-of-type) {
    padding-left: 16px;
    &::before {
      content: '|';
      position: absolute;
      top: 0;
      left: 0;
      color: #DCDFE6;
    }
  }
}
</style>
