<template>
  <el-form
    ref="ruleForm"
    :rules="rules"
    :model="ruleForm"
    label-width="130px"
    size="small"
    v-loading="loading"
  >
    <el-form-item label="上架规则名称" prop="ruleTitle">
      <el-input
        maxlength="30"
        show-word-limit
        placeholder="请输入上架规则名称"
        v-model="ruleForm.ruleTitle"
        style="width:340px"
      />
    </el-form-item>
    <el-form-item label="上架规则说明" prop="ruleExplanation">
      <el-input
        maxlength="50"
        show-word-limit
        placeholder="请输入上架规则说明"
        v-model="ruleForm.ruleExplanation"
        style="width:340px"
      />
    </el-form-item>
    <el-form-item label="适用人群" prop="memberType">
      <span v-if="$store.state.product.ruleMemberFilterClose==0" class="tips">【人群筛选器】类型的上架规则最多支持20条,目前已创建 <span style="color:#1890ff">{{ memberTypeTotal }}</span> 条</span>
      <div>
        <el-radio v-model="ruleForm.memberType" :label="1" v-if="$store.state.product.ruleMemberFilterClose==0">
          全部客户
        </el-radio>
        <el-radio v-model="ruleForm.memberType" :label="4">
          门店筛选
        </el-radio>
        <el-radio
          v-model="ruleForm.memberType"
          :label="3"
          :disabled="memberTypeTotal>=20&&isAdd"
          v-if="$store.state.product.ruleMemberFilterClose==0"
        >
          人群筛选器
        </el-radio>
      </div>
      <span class="tips">{{ tipsContent[ruleForm.memberType] }}</span>
    </el-form-item>
    <el-form-item v-show="ruleForm.memberType === 4">
      <vue-gic-store-new
        :isAdd="isAdd || !uuid"
        :uuid.sync="uuid"
        ref="storeGroup"
        @store-change="storeChange"
      />
    </el-form-item>
    <vue-gic-people
      v-show="ruleForm.memberType === 3&&$store.state.product.ruleMemberFilterClose==0"
      v-bind="storeParams"
      :projectName="projectName"
      :triggerReset="true"
      :useId="useId"
      :hasSearchData="hasSearchData"
      :sceneValue="sceneValue"
      ref="peopleFilter"
      @findFilter="findFilter"
      @getBackData="getBackData"
      @editShow="hasEditGicPeople=true"
    />
    <div>
      <el-form-item style="margin-top:50px" v-show="!isDialog">
        <el-button
          type="primary"
          size="small"
          @click="submit()"
          :loading="btnLoading"
        >
          确认
        </el-button>
      </el-form-item>
    </div>
  </el-form>
</template>

<script>
import request from '@/service/request';
export default {
  props: {
    isDialog: {
      default: false,
      type: Boolean,
    },
  },
  data () {
    const activityTimeVal = (rule, value, callback) => {
      callback(new Error('请填写'));
    };
    return {
      fixedWidth: document.documentElement.clientWidth - 200,
      ruleForm: {
        memberType: 1, // 1：全部顾客 3 人群筛选 4 门店筛选
      },
      rules: {
        ruleTitle: [
          { required: true, message: '请填写', trigger: 'blur' },
        ],
        activityTime: [
          { required: true, message: '请填写', trigger: 'blur', validator: activityTimeVal },
        ],
      },
      projectName: 'integral-mall',
      useId: '',
      hasSearchData: '',
      sceneValue: 'member', // 场景值
      hasEditGicPeople: false,
      isEdit: this.$route.meta.type === 'edit',
      isAdd: this.$route.meta.type === 'add',
      isCopy: this.$route.meta.type === 'copy',
      loading: false,
      btnLoading: false,
      uuid: '',
      memberTypeTotal: 0,
      tipsContent: {
        1: '商户下的所有客户都可见，请谨慎选择',
        4: '按照客户的门店归属来控制是否可见',
        3: '从商户所有客户中按照条件筛选来控制是否可见',
      },
    };
  },
  computed: {
    storeParams () {
      return !this.isAdd ? { creatorId: this.ruleForm.creatorId } : {};
    },
  },
  mounted () {
    if (!this.isAdd) {
      this.integralMallProRuleId = this.$route.params.id;
      this.getDatail(this.$route.params.id);
    }
    this.memberTypeNum();
  },
  methods: {
    /** 门店筛选器 */
    storeChange (storeId) {
      this.uuid = storeId;
    },
    /** 人群筛选器 */
    // 获取需要回显的数据, 供保存时候使用
    getBackData (val) {
      console.log(val);
      this.ruleForm.searchJson = val;
    },
    // 子组件触发父组件事件,返回过滤条件数据
    findFilter (val) {
      console.log(val);
      this.ruleForm.filterJson = val;
    },
    getDatail (integralMallProRuleId) {
      this.loading = true;
      request.get('/api-integral-mall/get-rule', { params: { integralMallProRuleId } }).then(res => {
        if (res.data.result) {
          this.ruleForm = res.data.result;
          if (this.ruleForm.memberType == 3) { // 人群筛选器回显
            this.hasSearchData = this.ruleForm.filterJson;
            this.useId = this.ruleForm.searchId;
            if (this.isCopy) {
              const form = new FormData();
              form.append('requestProject', 'integral-mall');
              form.append('id', this.ruleForm.searchId);
              request.post('/api-plug/get-screening-detail', form).then(res => {
                this.ruleForm.searchJson = res.data.result && res.data.result.detail;
              });
            }
          } else if (this.ruleForm.memberType == 4) { // 门店筛选器回显
            this.uuid = JSON.parse(this.ruleForm.filterJson).storeWidgetId;
          }
        }
      }).finally(() => {
        this.loading = false;
      });
    },
    submitRequest () {
      this.$refs.ruleForm.validate(val => {
        if (val) {
          let data = {};
          if (this.isCopy) {
            const { ruleTitle, ruleExplanation, filterJson, memberType, searchJson, showBack } = this.ruleForm;
            data = { ruleTitle, ruleExplanation, memberType, filterJson, searchJson, showBack };
          } else {
            data = this.ruleForm;
          }
          this.btnLoading = true;
          this.$emit('btnLoading');
          request.post('/api-integral-mall/add-update-rule', data).then(res => {
            const integralMallProRuleId = res.data.result;
            if (this.isDialog) {
              this.$emit('submit', { ...data, integralMallProRuleId });
            } else {
              this.$router.go(-1);
            }
          }).finally(() => {
            this.$emit('btnStop');
            this.btnLoading = false;
          });
        }
      });
    },
    async  submit () {
      if (this.ruleForm.memberType == 1) {
        this.ruleForm.filterJson = '';
        this.ruleForm.searchJson = '';
        this.ruleForm.searchId = '';
        this.submitRequest();
      } else if (this.ruleForm.memberType == 3) {
        if (this.hasEditGicPeople) {
          this.$refs.peopleFilter.confirmSet().then(async () => {
            const res = await this.echoData(this.ruleForm.filterJson);
            this.ruleForm.showBack = res.data.result;
            this.submitRequest();
          });
        } else {
          const res = await this.echoData(this.ruleForm.filterJson);
          this.ruleForm.showBack = res.data.result;
          this.submitRequest();
        }
      } else if (this.ruleForm.memberType == 4) {
        this.$refs.storeGroup.getStoreConfig().then(async (data) => {
          let type = 0;
          if (data.type != 0) {
            type = 1;
          }
          const res = await this.echoData2(this.uuid, data.type);
          const { data: { result: { result } } } = res;
          console.log(result);
          if (result) {
            this.ruleForm.showBack = result.map(item => item.name).join(',');
          } else {
            this.ruleForm.showBack = '所有门店';
          }
          this.ruleForm.filterJson = JSON.stringify({ storeMode: type, storeWidgetId: this.uuid });
          this.ruleForm.searchJson = '';
          this.ruleForm.searchId = this.uuid;
          this.submitRequest();
        });
      }
    },
    echoData (filterJson) { // 取得人群筛选器回显文字
      const form = new FormData();
      form.append('params', filterJson);
      form.append('requestProject', 'integral-mall');
      form.append('sceneCode', 'member');
      return request.post('/api-plug/screening-show-back', form);
    },
    echoData2 (key, type) { // 取得门店筛选器的文字回显
      const form = new FormData();
      form.append('key', key);
      form.append('selectType', type);
      form.append('currentPage', 1);
      form.append('pageSize', 20);
      return request.post('/api-plug/list-right-data', form);
    },
    memberTypeNum () {
      request.get('/api-integral-mall/list-rule', { params: { memberType: 3 } }).then(res => {
        this.memberTypeTotal = res.data.result.length || 0;
      });
    },
  },

};
</script>

<style scoped>
.gic-people--button{
  background: #f2f3f4;
    padding: 0 0 20px 124px;
}
</style>
