<!--
 * @Descripttion: 指标设置
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2020-11-09 10:05:27
 * @LastEditors: 无尘
 * @LastEditTime: 2020-11-09 10:26:18
-->
<!--  -->
<template>
  <div class="common-app-right" style="padding: 0" v-loading="loading">
    <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="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 placeholder="操作" @change="batchOperation">
          <el-option label="新增指标" :value="1" v-show="activeName === '0'"></el-option>
          <el-option label="编辑指标" :value="2"></el-option>
          <el-option label="修改编辑权限" :value="3" v-show="activeName === '0'"></el-option>
        </el-select>
      </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="searchChange">未设置业绩指标门店</el-checkbox>
          <el-checkbox v-model="search1.noAddMemberFlag" :true-label="1" :false-label="0" @change="searchChange">未设置新增会员指标门店</el-checkbox>
        </span>
      </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}">
            <div>{{ 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.performanceYearValue ? `￥${row.performanceYearValue}` : '未设置' }}
          </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="操作">
          <template>
            <el-button type="text">编辑</el-button>
            <el-button type="text" v-show="activeName === '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 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 } = 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: '0',
        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 || '0';
    this.applicationId = applicationId;
    const { staffId, wxEnterpriseId } = JSON.parse(localStorage.getItem('haoBanUser'));
    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 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();
    },
    // 获取年份
    getYearList() {
      getYearList('', { headers: { sign: this.brandId } }).then(res => {
        this.yearList = res.result || [];
      });
    },
    // 筛选条件变更
    searchChange() {
      this.handleCurrentChange(1);
    },
    // 门店分组change
    checkGroupIds(nodes) {
      console.log(nodes);
      this.search.storeParam = nodes.map(item => item[this.form.storeType === '1' ? 'storeGroupId' : 'tagId']).join(',');
    },
    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 {
  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;
    }
  }
}
</style>
