<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:#2F54EB">{{ 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="isDisabled"
          v-if="$store.state.product.ruleMemberFilterClose==0"
        >
          人群筛选器
        </el-radio>
        <el-radio v-model="ruleForm.memberType"
          :label="2"
          :disabled="isDisabled"
          v-if="$store.state.product.ruleMemberFilterClose==0">
          会员分组
        </el-radio>
      </div>
    </el-form-item>
    <el-form-item v-show="ruleForm.memberType === 4">
      <!-- <vue-gic-store-new
        :isAdd="isAdd || !uuid"
        :uuid.sync="uuid"
        ref="storeGroup"
        :creatorId="ruleForm.creatorId"
        @store-change="storeChange"
      /> -->
       <dm-store-selector
          :creatorId="ruleForm.creatorId"
           ref="storeGroup"
           @store-change="storeChange"
           v-if="canShowStoreSelector"
          :uuid="uuid">
        </dm-store-selector>
    </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"
    />
      <el-form-item v-show="ruleForm.memberType === 2" prop="selectedGroupIds" >
          <el-button v-if="!selectedGroupIds" size="small" @click="addMemberGroup">添加分组</el-button>
          <gic-new-member-group :visiable.sync="groupVisible"
              :selectedIds="selectedGroupIds"
              @change="confirmGroupDialog"
              ref="newMemberGroup"/>
      </el-form-item>
    <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('请填写'));
    };
    const selectedGroupIdsVal = (rule, value, callback) => {
      if (this.ruleForm.memberType === 2 && !this.selectedGroupIds) {
        callback(new Error('请选择分组'));
        return;
      }
      callback();
    };
    return {
      groupVisible: false,
      selectedGroupIds: '', // 被选中的客户分组id
      fixedWidth: document.documentElement.clientWidth - 200,
      memberType: 1,
      ruleForm: {
        memberType: 4, //  3 人群筛选 4 门店筛选
        creatorId: '',
      },
      rules: {
        ruleTitle: [
          { required: true, message: '请填写', trigger: 'blur' },
        ],
        activityTime: [
          { required: true, message: '请填写', trigger: 'blur', validator: activityTimeVal },
        ],
        selectedGroupIds: [
          { required: true, validator: selectedGroupIdsVal },
        ],
      },
      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,

    };
  },
  computed: {
    storeParams () {
      return !this.isAdd ? { creatorId: this.ruleForm.creatorId } : {};
    },
    isDisabled () {
      if (this.isAdd) {
        return this.memberTypeTotal >= 20;
      } else {
        return !(this.memberType == 3 || this.memberType == 2) && this.memberTypeTotal >= 20;
      }
    },
    canShowStoreSelector () {
      return this.isDialog || this.uuid || this.isAdd || this.memberType == 3 || this.memberType == 2;
    },
  },
  mounted () {
    if (!this.isAdd) {
      this.integralMallProRuleId = this.$route.params.id;
      this.getDatail(this.$route.params.id);
    }
    this.memberTypeNum();
  },
  methods: {
    addMemberGroup () {
      this.groupVisible = true;
    },
    /** 门店筛选器 */
    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) {
          const data = res.data.result;
          this.memberType = data.memberType;
          if (data.memberType == 3) { // 人群筛选器回显
            this.hasSearchData = data.filterJson;
            this.useId = data.searchId;
            if (this.isCopy) {
              const form = new FormData();
              form.append('requestProject', 'integral-mall');
              form.append('id', data.searchId);
              request.post('/api-plug/get-screening-detail', form).then(res => {
                data.searchJson = res.data.result && res.data.result.detail;
              });
            }
          } else if (data.memberType == 4) { // 门店筛选器回显
            this.uuid = JSON.parse(data.filterJson).storeWidgetId;
          } else if (data.memberType == 2) {
            this.selectedGroupIds = data.filterJson;
          }
          if (this.isCopy) {
            data.creatorId = localStorage.getItem('useId');
          }
          this.ruleForm = data;
        }
      }).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;
          }
          // console.log(data);
          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 () => {
            this.submitRequest();
          });
        } else {
          this.ruleForm.filterJson = '';
          this.ruleForm.searchJson = '';
          this.ruleForm.searchId = '';
          this.submitRequest();
        }
      } else if (this.ruleForm.memberType == 4) {
        this.$refs.storeGroup.getStoreConfig().then(async (data) => {
          this.ruleForm.filterJson = JSON.stringify({ storeMode: data.type, storeWidgetId: this.uuid });
          this.ruleForm.searchJson = '';
          this.ruleForm.searchId = this.uuid;
          this.submitRequest();
        });
      } else if (this.ruleForm.memberType == 2) {
        this.ruleForm.filterJson = this.selectedGroupIds;
        this.ruleForm.searchJson = '';
        this.ruleForm.searchId = '';
        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);
    },
    /** 客户分组 */
    confirmGroupDialog (arr, idStr) {
      this.selectedGroupIds = idStr;
      this.$refs.ruleForm.validateField('selectedGroupIds');
    },
    memberTypeNum () {
      Promise.all([request.get('/api-integral-mall/list-rule', { params: { memberType: 3 } }), request.get('/api-integral-mall/list-rule', { params: { memberType: 2 } })]).then(res => {
        // console.log(res);
        const total1 = res[0].data.result ? res[0].data.result.length : 0;
        const total2 = res[1].data.result ? res[1].data.result.length : 0;
        this.memberTypeTotal = total1 + total2;
      });
    },
  },

};
</script>

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