<!--
 * @Descripttion: 指标设置
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2020-11-09 10:05:27
 * @LastEditors: 无尘
 * @LastEditTime: 2020-12-02 09:06:36
-->
<!--  -->
<template>
  <div class="common-app-right" style="padding: 0">
    <el-tabs v-model="activeName" @tab-click="getData">
      <el-tab-pane label="已设置指标门店" name="0"></el-tab-pane>
      <el-tab-pane label="未设置指标门店" name="1"></el-tab-pane>
    </el-tabs>

    <div class="list-content">
      <div class="content-search">
        <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 v-model="search.performanceYear" placeholder="选择年份" style="width: 100px" @change="searchChange">
            <el-option v-for="item in yearList" :key="item" :label="item" :value="item"></el-option>
          </el-select>

          <span v-show="activeName === '0'">
            <el-select v-model="search.type" placeholder="全部指标类型" clearable @change="searchChange">
              <el-option label="业绩指标日权重" value="1"></el-option>
              <el-option label="业绩指标日指标" value="2"></el-option>
              <el-option label="新增会员日权重" value="3"></el-option>
              <el-option label="新增会员日指标" value="4"></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>

          </span>

          <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="171px"
            :brand-id="brandId"
            @checkGroupIds="checkGroupIds">
          </gic-select-group-mult>

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

        </div>

        <div class="selectColor">
          <el-select placeholder="批量操作" style="width:101px" @change="batchOperation" :disabed="!multipleSelection || !multipleSelection.length">
            <el-option label="编辑指标" :value="2"></el-option>
            <el-option label="修改编辑权限" :value="3" v-show="activeName === '0'"></el-option>
          </el-select>
          <el-button type="primary" @click="batchOperation(1)" v-show="activeName === '0'">新增指标</el-button>
        </div>
      </div>

      <div class="content-data" v-show="activeName === '1'">
        <div>
          <!-- <span class="color2">年业绩指标：¥ </span>
          <span class="color1">100,000</span>
          <span class="color2">年新增会员指标：¥  </span>
          <span class="color1">100,000</span> -->
        </div>

        <span>
          <el-checkbox v-model="search1.noPerformanceFlag" :true-label="1" :false-label="0" @change="val => checkboxChange(val, 'noPerformanceFlag')">未设置业绩指标门店</el-checkbox>
          <el-checkbox v-model="search1.noAddMemberFlag" :true-label="1" :false-label="0" @change="val => checkboxChange(val, 'noAddMemberFlag')">未设置新增会员指标门店</el-checkbox>
        </span>
      </div>

      <el-table
        :data="tableData"
        v-loading="loading"
        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}">
            <div class="ellipsis">{{ row.storeName || '--' }}</div>
            <div style="color: #909399;font-size:12px">{{ row.storeCode || '--' }}</div>
          </template>
        </el-table-column>
        <el-table-column label="年业绩指标" show-overflow-tooltip>
          <template slot-scope="{row}">
            {{ row.performaneceYearValue ? `￥${row.performaneceYearValue}` : '未设置' }}
          </template>
        </el-table-column>
        <el-table-column label="年新增会员指标" show-overflow-tooltip>
          <template slot-scope="{row}">
            {{ row.addMemberValue ? `${row.addMemberValue}` : '未设置' }}
          </template>
        </el-table-column>
        <el-table-column label="编辑权限" show-overflow-tooltip>
          <template slot-scope="{row}">
            {{ [ '店长不可编辑', '店长可编辑' ][row.storeEdit] || '--' }}
          </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"
              @click="$router.push({
                path: '/edit-store-quota',
                query: {
                  applicationId,
                  tab: activeName,
                  storeInfoId: row.storeInfoId,
                  storeName: row.storeName,
                  edit: '1',
                  year: search.performanceYear,
                  performanceFlag: search1.noPerformanceFlag,
                  addMemberFlag: search1.noAddMemberFlag
                }
              })">
              编辑指标
            </el-button>
            <el-button
              type="text"
              @click="$router.push({
                path: '/edit-store-quota',
                query: {
                  applicationId,
                  tab: activeName,
                  storeInfoId: row.storeInfoId,
                  storeName: row.storeName,
                  storeEdit: row.storeEdit,
                  edit: '3',
                  single: '1',
                  year: search.performanceYear,
                }
              })">
              编辑权限
            </el-button>
            <el-button type="text" v-show="activeName === '0'" @click="delStorePerformance(row.storeInfoId)">删除</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 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 { getYearList, getStorePerformanceList, getNoStorePerformanceList, delStorePerformance } = fetch;

export default {
  name: 'QuotaSet',
  components: { gicSelectGroupMult, gicSelectTag },
  props: {
    brandId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      activeName: '',
      applicationId: '',
      haoban: {},

      search: {
        search: '',
        performanceYear: new Date().getFullYear(),
        type: '',
        storeEdit: '', // 1店长可编辑，0店长不可编辑
        storeType: '1', // 1门店分组，2门店标签
        storeParam: '',
      },
      search1: {
        noPerformanceFlag: 1,
        noAddMemberFlag: 0
      },

      multipleSelection: [],
      tableData: [],
      loading: false,
      page: {
        pageNum: 1,
        pageSize: 20,
        total: 0
      },
      yearList: [],
      typeList: [
        { performanceType: 1, performanceSubType: 1 },
        { performanceType: 1, performanceSubType: 2 },
        { performanceType: 2, performanceSubType: 1 },
        { performanceType: 2, performanceSubType: 2 },
      ]
    };
  },

  created() {
    const { tab, applicationId } = this.$route.query;
    this.activeName = tab !== 'undefined' && tab ? tab : '0';
    this.applicationId = applicationId;
    const { staffId, wxEnterpriseId } = localStorage.getItem('haoBanUser') ? JSON.parse(localStorage.getItem('haoBanUser')) : { staffName: '', staffId: '', wxEnterpriseId: '' };
    this.haoban = { staffId, wxEnterpriseId };
  },
  // 生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    this.$emit('showTab', '/quota-set');
    this.$emit('change-nav', [ { name: '指标设置' } ]);
    this.getData();
    this.getYearList();
  },

  // methods
  methods: {
    getData() {
      this.loading = true;
      const { storeType, storeParam, type } = this.search;
      let params = {
        ...this.search,
        ...this.haoban,
        ...this.page,
        enterpriseId: this.brandId,
        storeType: storeParam ? storeType : '',
      };

      if (this.activeName === '0') { // 已设置
        params = {
          ...params,
          ...this.typeList[type - 1]
        };
      } else if (this.activeName === '1') { // 未设置
        params = {
          ...params,
          ...this.search1
        };
      }

      [ getStorePerformanceList, getNoStorePerformanceList ][this.activeName](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) {
      switch (val) {
        case 1: // 新建
          return this.$router.push({ path: '/edit-store-quota', query: { applicationId: this.applicationId } });
        case 2: // 批量编辑
          if (!this.multipleSelection || !this.multipleSelection.length) return this.$message.warning('请选择指标门店');
          if (!this.search.type && this.activeName == 0) return this.$message.warning('请选择指标类型');

          localStorage.setItem('targetStoreInfoIds', JSON.stringify(this.multipleSelection));
          return this.$router.push({
            path: '/edit-store-quota',
            query: {
              applicationId: this.applicationId,
              tab: this.activeName,
              edit: '2',
              year: this.search.performanceYear,
              type: this.search.type,
              performanceFlag: this.search1.noPerformanceFlag,
              addMemberFlag: this.search1.noAddMemberFlag
            }
          });
        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 } });
        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();
    },
    // 获取年份
    getYearList() {
      getYearList('', { headers: { sign: this.brandId } }).then(res => {
        this.yearList = res.result || [];
      });
    },
    // 筛选条件变更
    searchChange() {
      this.handleCurrentChange(1);
    },
    // 未设置checkbox变更
    checkboxChange(val, type) {
      this.$nextTick(() => {
        const { noPerformanceFlag, noAddMemberFlag } = this.search1;
        if (noPerformanceFlag === 0 && noAddMemberFlag === 0) {
          this.search1[type] = 1;
          return this.$message.warning('请至少勾选一项');
        }
        this.searchChange();
      });
    },
    // 门店分组change
    checkGroupIds(nodes) {
      this.search.storeParam = nodes.map(item => item[this.search.storeType === '1' ? 'storeGroupId' : 'storeTagId']).join(',');
      this.searchChange();
    },
    storeChange() {
      this.search.storeParam = '';
      this.searchChange();
    },
    // 删除
    delStorePerformance(storeInfoId) {
      this.$confirm('确定删除该指标门店?', '提示', {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let params = {
          storeInfoId,
          performanceYear: this.search.performanceYear
        };
        delStorePerformance(params, { headers: { sign: this.brandId } })
          .then(res => {
            this.$message.success('删除成功');
            if (this.tableData.length < 2 && this.page.pageNum > 1) {
              --this.page.pageNum;
            }
            this.getData();
          });
      });
    }
  },
  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) {
      const { staffId, wxEnterpriseId } = localStorage.getItem('haoBanUser') ? JSON.parse(localStorage.getItem('haoBanUser')) : { staffName: '', staffId: '', wxEnterpriseId: '' };
      this.haoban = { staffId, wxEnterpriseId };
      val && this.getData();
    }
  },
};
</script>
<style lang='less' scoped>
.list-content {
  padding: 5px 20px 20px;
  .el-input {
    width: 180px;
    margin-right: 10px;
  }
  .el-select {
    width: 148px;
    margin-right: 10px;
  }
  .el-date-picker {
    margin-right: 10px;
  }
}
// .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;
    }
  }
}
.ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.selectColor {
  /deep/.el-input__inner::-webkit-input-placeholder {
    color: #606266;
  }
  /deep/.el-input__inner::-moz-input-placeholder {
    color: #606266;
  }
  /deep/.el-input__inner::-ms-input-placeholder {
    color: #606266;
  }
}
</style>
