<!--
 * @Descripttion: 编辑门店指标
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2020-11-09 10:40:12
 * @LastEditors: 无尘
 * @LastEditTime: 2020-11-09 10:41:18
-->
<template>
  <div class="common-app-right">
    <el-alert
      show-icon
      :closable="false">
      <template slot="title">
        <div>1.下发类型修改后、日权重/日指标修改后、指标设置立即生效，修改后数据统计次日生效</div>
        <div>2.修改当月指标会导致已完善的日指标重新下发及完善。请谨慎设置</div>
      </template>
    </el-alert>

    <el-form :model="form" ref="form" :rules="rules" label-width="180px" hide-required-asterisk>
      <el-form-item label="选择年份" prop="performanceYear">
        <el-select v-model="form.performanceYear" placeholder="请选择年份" v-if="!edit">
          <el-option v-for="item in yearList" :key="item" :label="item" :value="item"></el-option>
        </el-select>
        <span v-else>{{ form.performanceYear }}</span>
      </el-form-item>

      <el-form-item label="选择门店" prop="storeValue">
        <template v-if="!edit">
          <el-radio-group v-model="form.storeMode" @change="storeModeChange">
            <el-radio :label="0">所有门店</el-radio>
            <el-radio :label="1">选择分组</el-radio>
            <el-radio :label="2">选择门店</el-radio>
          </el-radio-group>

          <customer-store-group v-if="form.storeMode == 1" :brand-id="brandId" :select-group="storeValue" @checkGroupIds="checkGroupIds"></customer-store-group>
          <customer-store v-if="form.storeMode == 2" :brand-id="brandId" :select-store="storeValue" @checkStoreIds="checkGroupIds"></customer-store>
        </template>
        <span v-else>{{ targetStoreInfoIds.map(item => item.storeName).join('；') }}</span>
      </el-form-item>

      <el-form-item label="指标类型（必填一项）" prop="type" v-if="!edit || ['1', '2'].includes(edit)"> <!-- 新增 || 编辑、批量编辑 -->
        <el-checkbox v-model="form.performanceFlag" :true-label="1" :false-label="0" :disabled="edit === '2' || preDisabled">
          业绩指标（元）
          <el-select v-model="form.performanceSubType" style="width: 240px;margin: 0 20px 20px 48px" :disabled="form.performanceFlag == 0 || edit === '2'">
            <el-option v-for="item in targetList" :key="item.name" :label="item.name" :value="item.val"></el-option>
          </el-select>
          <span class="color2">设置{{ ['日权重', '日指标'][form.performanceSubType-1] }}，则需先设置月指标，再设置门店{{ ['日权重', '日指标额'][form.performanceSubType-1] }}。指标会计算每日完成度。</span>
        </el-checkbox>
        <month-target
          ref="monthTargetRef1"
          v-show="form.performanceFlag == 1"
          is-precision
          :is-batch="edit === '2'"
          :year="form.performanceYear"
          :data="performanceCallback"
          @change="val => monthTargetChange(val, 'performanceVal')" />

        <el-checkbox v-model="form.addMemberFlag" :true-label="1" :false-label="0" :disabled="edit === '2' || preDisabled">
          新增会员指标（人）
          <el-select v-model="form.addMemebrSubType" style="width: 240px;margin: 0 20px 20px 21px" :disabled="form.addMemberFlag == 0 || edit === '2'">
            <el-option v-for="item in targetList" :key="item.name" :label="item.name" :value="item.val"></el-option>
          </el-select>
          <span class="color2">设置{{ ['日权重', '日指标'][form.addMemebrSubType-1] }}，则需先设置月指标，再设置门店{{ ['日权重', '日指标额'][form.addMemebrSubType-1] }}。指标会计算每日完成度。</span>
        </el-checkbox>

        <month-target
          ref="monthTargetRef2"
          v-show="form.addMemberFlag == 1"
          :is-batch="edit === '2'"
          :year="form.performanceYear"
          :data="addMemberCallback"
          no-icon
          @change="val => monthTargetChange(val, 'addMemberVal')" />
      </el-form-item>

      <el-form-item label="指标编辑权限" prop="storeEdit" v-if="edit === '3' || !edit">
        <el-checkbox v-model="form.storeEdit" :true-label="1" :false-label="0">店长可修改指标</el-checkbox>
      </el-form-item>

      <el-form-item label="">
        <el-button type="primary" @click="confirm" :loading="loading">保存</el-button>
      </el-form-item>
    </el-form>

  </div>
</template>

<script>
import customerStoreGroup from '@/components/app/my-customer/customer-store-group.vue';
import customerStore from '@/components/app/my-customer/customer-store.vue';
import MonthTarget from './MonthTarget.vue';
import fetch from '@/api/target-manage-app.js';
const { saveStorePerformance, batchSettingRight, batchEditStorePerformance, editStorePerformance, getSingleStorePerformanceDetail } = fetch;

export default {
  name: 'EditStoreQuota',
  components: { customerStoreGroup, customerStore, MonthTarget },
  props: {
    brandId: {
      type: String,
      default: ''
    }
  },
  data() {
    const storeCheck = (rule, value, callback) => {
      this.$nextTick(() => {
        const { storeMode, storeValue } = this.form;
        if (storeMode === 0) callback();
        if (!storeValue || !storeValue.length) callback(new Error('请选择分组或门店'));
        callback();
      });
    };
    return {
      loading: false,
      form: {
        performanceYear: '', // 年
        storeMode: 0, // 0,所有门店，1选择分组，2部门门店
        storeValue: [], // 选择的值aaa,bbb,ccc
        storeEdit: 0, // 1门店可编辑，0不可
        performanceFlag: 0, // 业绩指标 1已勾选
        performanceSubType: 1, // 业绩指标：1，日权重，2，指标额
        addMemberFlag: 0, // 新增会员指标1已勾选
        addMemebrSubType: 1, // 新增会员指标：1，日权重，2，指标额
      },
      rules: {
        performanceYear: [ { required: true, message: '请选择年份', trigger: 'blur' } ],
        storeValue: [ { required: true, validator: storeCheck, trigger: [ 'blur', 'change' ] } ],
      },

      targetList: [
        { name: '日权重', val: 1 },
        { name: '日指标', val: 2 }
      ],
      yearList: [ new Date().getFullYear(), new Date().getFullYear() + 1 ],

      performanceCallback: null, // 回显数据
      performanceVal: null,
      addMemberCallback: null, // 回显数据
      addMemberVal: null,

      targetStoreInfoIds: [], // 批量编辑的门店
      edit: '', // 3：批量编辑权限

      bread: [ { name: '指标设置', path: '/quota-set' }, { name: '新建指标' } ],

      typeList: [
        { performanceFlag: 1, performanceSubType: 1 },
        { performanceFlag: 1, performanceSubType: 2 },
        { addMemberFlag: 1, performanceSubType: 1 },
        { addMemberFlag: 1, performanceSubType: 2 },
      ],
      preDisabled: false // 未设置指标禁用
    };
  },
  created() {
    this.init();
    this.$emit('change-nav', this.bread);
  },
  mounted() {
    this.$emit('showTab', '/quota-set');
  },
  methods: {
    async init() { // 初始化
      // 修改面包屑
      const { applicationId, edit, year, storeEdit, storeInfoId, storeName, tab, type, performanceFlag, addMemberFlag, single } = this.$route.query;
      this.bread[0].path += `?applicationId=${applicationId}&tab=${tab}`;
      this.bread[1].name = edit ? '编辑指标' : '新建指标';

      switch (edit) {
        case '1':// 单个编辑
          this.form.performanceYear = year;
          this.targetStoreInfoIds = [ { storeName, storeInfoId } ];
          await this.callback({ year, storeInfoId });
          if (tab === '1') { // 未设置指标编辑
            this.preDisabled = true;
            this.form.performanceFlag = performanceFlag == '1' ? 1 : this.form.performanceFlag;
            this.form.addMemberFlag = addMemberFlag == '1' ? 1 : this.form.addMemberFlag;
          }
          break;

        case '2':// 批量编辑
          this.targetStoreInfoIds = JSON.parse(localStorage.getItem('targetStoreInfoIds'));
          this.form = {
            ...this.form,
            performanceYear: year,
          };
          if (tab === '1') { // 未设置指标编辑
            this.form.performanceFlag = performanceFlag == '1' ? 1 : this.form.performanceFlag;
            this.form.addMemberFlag = addMemberFlag == '1' ? 1 : this.form.addMemberFlag;
          } else {
            this.form = {
              ...this.form,
              ...this.typeList[type - 1], // 指标类型批量的初始值
            };
          }
          break;

        case '3':// 批量/权限
          if (single) {
            this.form.storeEdit = Number(storeEdit);
            this.targetStoreInfoIds = [ { storeName, storeInfoId } ];
          } else {
            this.targetStoreInfoIds = JSON.parse(localStorage.getItem('targetStoreInfoIds'));
          }
          this.form.performanceYear = year;
          break;

        default:
          break;
      }

      this.edit = edit;
    },
    // 编辑回显
    callback({ year, storeInfoId }) {
      const { staffId, wxEnterpriseId } = JSON.parse(localStorage.getItem('haoBanUser'));
      let params = {
        storeInfoId,
        wxEnterpriseId,
        performanceYear: year,
        submitStaffId: staffId,
        enterpriseId: this.brandId
      };
      return getSingleStorePerformanceDetail(params, { headers: { sign: this.brandId } })
        .then(res => {
          const { addMemebrValue, performanceValue } = res.result;
          this.form = { ...this.form, ...res.result };
          addMemebrValue && (this.addMemberCallback = JSON.parse(addMemebrValue));
          performanceValue && (this.performanceCallback = JSON.parse(performanceValue));
        });
    },
    // 获取组件的值
    checkGroupIds(val) {
      this.form.storeValue = JSON.parse(JSON.stringify(val));
    },
    // 返值
    monthTargetChange(val, str) {
      this[str] = val;
    },
    // 保存
    confirm() {
      this.$refs.form.validate(valid => {
        if (!valid) return;
        const { performanceFlag, addMemberFlag, storeValue, performanceYear, storeMode, storeEdit } = this.form;
        if (this.edit !== '3' && !performanceFlag && !addMemberFlag) return this.$message.warning('指标类型必填一项');
        if (performanceFlag && this.$refs.monthTargetRef1.validate()) return this.$message.warning('请完善业绩指标');
        if (addMemberFlag && this.$refs.monthTargetRef2.validate()) return this.$message.warning('请完善新增会员指标');

        this.loading = true;
        const { staffName, staffId, wxEnterpriseId } = JSON.parse(localStorage.getItem('haoBanUser'));
        let params = {
          wxEnterpriseId,
          submitStaffName: staffName,
          submitStaffId: staffId,
          enterpriseId: this.brandId,
        };

        if (this.edit === '1') { // 单个编辑
          params = {
            ...this.form,
            ...params,
            storeEdit,
            performanceValue: this.filterTargetVal('performanceVal', performanceYear),
            addMemebrValue: this.filterTargetVal('addMemberVal', performanceYear),
            storeInfoId: this.targetStoreInfoIds[0].storeInfoId,
            storeMode: undefined,
            storeValue: undefined
          };
        } else if (this.edit === '2') { // 批量编辑
          params = {
            ...this.form,
            ...params,
            performanceValue: this.filterTargetVal('performanceVal', performanceYear),
            addMemebrValue: this.filterTargetVal('addMemberVal', performanceYear),
            storeInfoIds: this.targetStoreInfoIds.map(item => item.storeInfoId).join(','),
            storeMode: undefined,
            storeValue: undefined
          };
        } else if (this.edit === '3') { // 批量权限
          params = {
            ...params,
            performanceYear,
            storeEdit,
            storeInfoIds: this.targetStoreInfoIds.map(item => item.storeInfoId).join(','),
          };
        } else if (!this.edit) { // 新增
          params = {
            ...this.form,
            ...params,
            // eslint-disable-next-line
            storeValue: storeValue.map(item => storeMode == 1 ? item.storeGroupId : item.storeInfoId).join(','),
            performanceValue: this.filterTargetVal('performanceVal', performanceYear),
            addMemebrValue: this.filterTargetVal('addMemberVal', performanceYear)
          };
        }

        [ saveStorePerformance, editStorePerformance, batchEditStorePerformance, batchSettingRight ][this.edit || 0](params, { headers: { sign: this.brandId } })
          .then(res => {
            this.$message.success('保存成功');
            this.$router.push(this.bread[0].path);
          })
          .finally(() => this.loading = false);
      });
    },
    // 转化传给后端的数据
    filterTargetVal(type, year) {
      if (!type) return '';
      return JSON.stringify(this[type].map(item => {
        return {
          performanceYm: `${year.toString()}-${item.num}`,
          performanceValue: item.val !== undefined ? item.val : ''
        };
      }));
    },
    storeModeChange() {
      this.form.storeValue = '';
    }
  },
  watch: {
    brandId(val) {
      val && this.init();
    }
  }
};
</script>

<style lang="less" scoped>
.el-alert {
  width: 590px;
  margin-bottom: 20px;
  font-size: 13px;
}
.color2 {
  color: #606266;
  font-size: 12px;
}
</style>