<!--
 * @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="请选择年份">
          <el-option v-for="item in yearList" :key="item" :label="item" :value="item"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="选择门店" prop="storeValue">
        <el-radio-group v-model="form.storeMode">
          <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>
      </el-form-item>

      <el-form-item label="指标类型（必填一项）" prop="type">
        <el-checkbox v-model="form.performanceFlag" :true-label="1" :false-label="0">
          业绩指标（元）
          <el-select v-model="form.performaceSubType" style="width: 240px;margin: 0 20px 20px 48px" :disabled="form.performanceFlag == 0">
            <el-option v-for="item in targetList" :key="item.name" :label="item.name" :value="item.val"></el-option>
          </el-select>
          <span class="color2">设置日指标，则需先设置月指标，再设置门店日指标额。指标会计算每日完成度。</span>
        </el-checkbox>
        <month-target ref="monthTargetRef1" v-show="form.performanceFlag == 1" :year="form.performanceYear" :data="performanceCallback" @change="val => monthTargetChange(val, 'performanceVal')" />

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

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

      <el-form-item label="指标编辑权限" prop="storeEdit">
        <el-checkbox v-model="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 { getYearList, saveStorePerformance } = 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已勾选
        performaceSubType: 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: [],

      performanceCallback: null, // 回显数据
      performanceVal: null,
      addMemberCallback: null, // 回显数据
      addMemberVal: null,
    };
  },
  mounted() {
    this.$emit('showTab', '/quota-set');
    let bread = [ { name: '指标设置', path: '/quota-set' }, { name: '编辑指标' } ];
    // 修改面包屑
    this.$emit('change-nav', bread);
    this.getYearList();
  },
  methods: {
    // 获取组件的值
    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 } = this.form;
        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 = {
          ...this.form,
          wxEnterpriseId,
          submitStaffName: staffName,
          submitStaffId: staffId,
          enterpriseId: this.brandId,
          storeValue: storeValue.map(item => item.storeGroupId).join(','),
          performanceValue: this.filterTargetVal('performanceVal', performanceYear),
          addMemebrValue: this.filterTargetVal('addMemberVal', performanceYear)
        };
        saveStorePerformance(params, { headers: { sign: this.brandId } })
          .then(res => {
            this.$message.success('保存成功');
            this.$router.go(-1);
          })
          .finally(() => this.loading = false);
      });
    },
    // 获取年份
    getYearList() {
      getYearList('', { headers: { sign: this.brandId } }).then(res => {
        this.yearList = res.result || [];
      });
    },
    // 转化传给后端的数据
    filterTargetVal(type, year) {
      if (!type) return '';
      return JSON.stringify(this[type].map(item => {
        return {
          performanceYm: `${year.toString()}-${item.num}`,
          performanceValue: item.val
        };
      }));
    }
  },
  watch: {
    brandId(val) {
      // val && this.getData();
    }
  }
};
</script>

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