<template>
  <div class="add-rules">
    <el-form :model="myCustomData" :rules="rules" ref="myCustomData" label-width="100px">
      <el-form-item label="策略名称" prop="strategyName">
        <el-input v-model="myCustomData.strategyName" style="width: 460px" placeholder="请输入策略名称" maxlength="10" show-word-limit></el-input>
      </el-form-item>
      <el-form-item label="门店类型" prop="storeType">
        <el-checkbox-group v-model="myCustomData.storeType">
          <el-checkbox v-for="el in storeTypes" :key="el.value" :disabled="selectedTypes.includes(el.value)" :label="el.value">
            {{ el.label }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="设置项" prop="options">
        <div class="setting-item">
          <el-checkbox v-model="myCustomData.mainStoreFlag" :true-label="1" :false-label="0" @change="onOptionsChange">展示服务门店客户</el-checkbox>
          <div class="set-tip-text">保存勾选项后，门店导购和店长可查看本门店作为服务门店名下客户</div>
        </div>
        <div class="setting-item">
          <el-checkbox v-model="myCustomData.minorStoreFlag" :true-label="1" :false-label="0" @change="onOptionsChange">展示协管门店客户</el-checkbox>
          <div class="set-tip-text">保存勾选项后，门店导购和店长可查看本门店作为协管门店名下客户</div>
        </div>
        <div class="setting-item">
          <el-checkbox v-model="myCustomData.openCardStoreFlag" :true-label="1" :false-label="0" @change="onOptionsChange">展示开卡门店客户</el-checkbox>
          <div class="set-tip-text">保存勾选项后，门店导购和店长可查看本门店作为开卡门店名下客户</div>
        </div>
        <div class="setting-item">
          <el-checkbox v-model="myCustomData.showFreezeFlag" :true-label="1" :false-label="0" @change="onOptionsChange">展示冻结会员</el-checkbox>
          <div class="set-tip-text">保存勾选项后，门店导购和店长可查看本门店冻结会员</div>
        </div>
        <div class="setting-item">
          <el-checkbox v-model="myCustomData.isSeeAuthMember" :true-label="1" :false-label="0" @change="onOptionsChange">展示已开卡会员</el-checkbox>
          <div class="set-tip-text">保存勾选项后，门店导购和店长可查看本门店微信会员（不含未开卡会员）及POS会员，不勾选将展示微信会员（即微信总量，含未开卡会员）及POS会员</div>
        </div>
        <div class="setting-item">
          <el-checkbox v-model="myCustomData.clerkSeeOtherFlag" :true-label="1" :false-label="0" @change="onOptionsChange">允许导购查看其他导购客户</el-checkbox>
          <div class="set-tip-text">保存勾选项后，门店导购可查看本门店其他导购名下客户</div>
        </div>
      </el-form-item>
    </el-form>
    <hb-form-bottom>
      <el-button @click="$router.go(-1)">返回</el-button>
      <el-button type="primary" :loading="loading" @click="onSave">保 存</el-button>
    </hb-form-bottom>
  </div>
</template>
<script>
import errMsg from '@/common/js/error';
import { postRequest, getRequest } from '@/api/api';

export default {
  name: 'AddMemberShowRules',
  props: {
    brandId: {
      type: String,
      default() {
        return '';
      }
    }
  },
  data() {
    const valiStoreType = (rules, value, callback) => {
      const data = value.filter(el => !this.selectedTypes.includes(el));
      if (this.myCustomData.storeType.includes('-1')) {
        return callback();
      }
      if (this.storeTypes.every(el => this.selectedTypes.includes(el.value))) {
        return callback(new Error('一种门店类型仅能包含在一个特殊策略中，当前所有门店类型已被其它特殊策略占用，无法创建'));
      }
      if (data.length == 0) {
        return callback(new Error('请选择门店类型'));
      }
      callback();
    };
    return {
      // 门店类型（0:自营,1:联营,2:代理(加盟),3:代销,4:托管）
      // -1:全部，也就是通用策略、默认策略
      storeTypes: [
        { label: '自营', value: '0' },
        { label: '联营', value: '1' },
        { label: '代理', value: '2' },
        { label: '代销', value: '3' },
        { label: '托管', value: '4' }
      ],
      selectedTypes: [],
      wxEnterpriseRelatedId: JSON.parse(sessionStorage.getItem('userInfos')).wxEnterpriseId,
      myCustomData: {
        memberManageSettingId: '', // 会员设置id，更新时必传
        strategyName: '',
        storeType: [], //门店类型	-1:全部；1:自营；2:联营；3:代理；4:代销；5:托管
        mainStoreFlag: 0, // 服务门店显示，1显示0不现实
        minorStoreFlag: 0, // 协管门店显示，1显示0不显示
        openCardStoreFlag: 0, // 开卡门店显示，1显示0不显示
        clerkSeeOtherFlag: 0, // 导购查看其他导购，1显示0不显示
        showFreezeFlag: 0,
        isSeeAuthMember: 0,
        options: ''
      },
      rules: {
        strategyName: { required: true, message: '请输入策略名称', trigger: 'blur' },
        storeType: { required: true, validator: valiStoreType, trigger: 'blur' },
        options: { required: true, message: '请选择设置项', trigger: 'blur' }
      },
      loading: false
    };
  },
  methods: {
    onOptionsChange() {
      const { mainStoreFlag, minorStoreFlag, openCardStoreFlag, clerkSeeOtherFlag, showFreezeFlag, isSeeAuthMember } = this.myCustomData;
      const flag = mainStoreFlag == 1 || minorStoreFlag == 1 || openCardStoreFlag == 1 || clerkSeeOtherFlag == 1 || showFreezeFlag == 1 || isSeeAuthMember == 1;
      this.myCustomData.options = flag ? 1 : '';
    },
    getSettingList() {
      getRequest('/haoban-app-customer-web/customer/find-member-manage-setting-list', {}).then(res => {
        const { code, result } = res.data || {};
        if (code != 0) {
          errMsg.errorMsg(res.data);
          return;
        }
        // storeType = -1时为通用策略
        // 通用策略不能修改门店类型
        if (this.myCustomData.storeType.includes('-1')) return;
        if (Array.isArray(result)) {
          this.selectedTypes = result.reduce((types, el) => {
            if (typeof el.storeType == 'string' && el.memberManageSettingId != this.myCustomData.memberManageSettingId) {
              let storeTypes = el.storeType.split(',');
              storeTypes = storeTypes.filter(el => !types.includes(el));
              types = types.concat(storeTypes);
            }
            return types;
          }, []);
          this.myCustomData.storeType = this.myCustomData.storeType.concat(this.selectedTypes);
        }
        this.$nextTick(() => {
          this.rules.storeType.trigger = 'change';
        });
      });
    },
    onSave() {
      this.loading = true;
      this.onOptionsChange();
      this.$refs.myCustomData.validate(vali => {
        if (!vali) {
          this.loading = false;
          return;
        }
        const { memberManageSettingId, strategyName, storeType, mainStoreFlag, minorStoreFlag, openCardStoreFlag, clerkSeeOtherFlag, showFreezeFlag, isSeeAuthMember } = this.myCustomData;
        const params = { memberManageSettingId, strategyName, mainStoreFlag, minorStoreFlag, openCardStoreFlag, clerkSeeOtherFlag, showFreezeFlag, isSeeAuthMember };
        params.storeType = storeType.filter(el => !this.selectedTypes.includes(el)).join(',');
        postRequest('/haoban-app-customer-web/customer/save-member-show-setting', params)
          .then(res => {
            const { errorCode } = res.data || {};
            if (errorCode != 1) {
              errMsg.errorMsg(res.data);
              return;
            }
            this.$message.success('保存成功');
            this.$router.go(-1);
          })
          .finally(() => (this.loading = false));
      });
    },
    getShowSet() {
      postRequest('/haoban-app-customer-web/customer/find-member-manage-setting-detail', { memberManageSettingId: this.myCustomData.memberManageSettingId }).then(res => {
        const { code, result } = res.data || {};
        if (code != 0) {
          errMsg.errorMsg(res.data);
          return;
        }
        const { strategyName, storeType, mainStoreFlag, minorStoreFlag, openCardStoreFlag, clerkSeeOtherFlag, showFreezeFlag, isSeeAuthMember } = result || {};
        Object.assign(this.myCustomData, {
          strategyName,
          storeType: this.selectedTypes.concat(typeof storeType == 'string' ? storeType.split(',') : []),
          mainStoreFlag,
          minorStoreFlag,
          openCardStoreFlag,
          clerkSeeOtherFlag,
          showFreezeFlag,
          isSeeAuthMember
        });
        // storeType = -1时为通用策略
        // 通用策略不能修改门店类型
        if (storeType == -'1') {
          this.selectedTypes = this.storeTypes.map(el => el.value);
          this.myCustomData.storeType = this.storeTypes.map(el => el.value);
          this.myCustomData.storeType.push('-1');
        }
        this.$nextTick(() => {
          this.rules.options.trigger = 'change';
        });
      });
    }
  },
  created() {
    this.getSettingList();
    if (this.$route.query.id) {
      this.myCustomData.memberManageSettingId = this.$route.query.id;
      this.getShowSet();
    }
  }
};
</script>
<style lang="scss" scoped>
.add-rules {
  padding: 20px;
}
.setting-item {
  & + .setting-item {
    margin-top: 16px;
  }
  .set-tip-text {
    padding: 0 0 0 25px;
    font-size: 12px;
    font-weight: 400;
    color: #909399;
    line-height: 17px;
  }
}
</style>
