<template>
  <div class="mall-section-container">
    <div class="mall-content-section">
      <div class="mall-content-title">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '' }">
            <a href="/report/#/memberSummary">首页</a>
          </el-breadcrumb-item>
          <el-breadcrumb-item>积分商城</el-breadcrumb-item>
          <el-breadcrumb-item>商品</el-breadcrumb-item>
          <el-breadcrumb-item :to="{ path: '/ruleList' }">
            上架规则
          </el-breadcrumb-item>
          <el-breadcrumb-item>{{ breadcrumbTitle }}</el-breadcrumb-item>
        </el-breadcrumb>
        <h3>
          <span>{{ breadcrumbTitle }}</span>
        </h3>
      </div>
      <div class="section">
        <el-form
          ref="ruleForm"
          :rules="rules"
          :model="ruleForm"
          label-width="160px"
          size="small"
          v-loading="loading"
        >
          <el-form-item label="上架规则名称" prop="ruleTitle">
            <el-input
              maxlength="12"
              show-word-limit
              placeholder="请输入上架规则名称"
              v-model="ruleForm.ruleTitle"
              clearable
              @clear="ruleForm.ruleTitle=''"
              style="width:340px"
            />
          </el-form-item>
          <el-form-item label="上架规则名称备注" prop="ruleExplanation">
            <el-input
              maxlength="30"
              show-word-limit
              placeholder="请输入上架规则说明"
              v-model="ruleForm.ruleExplanation"
              style="width:340px"
            />
          </el-form-item>
          <el-form-item label="适用人群" prop="memberType">
            <span class="tips">【会员筛选】类型的上架规则最多支持20条,目前已创建 <span style="color:#1890ff">{{ memberTypeTotal }}</span> 条</span>
            <div>
              <el-radio v-model="ruleForm.memberType" :label="1">
                全部会员
              </el-radio>
              <el-radio v-model="ruleForm.memberType" :label="4">
                门店筛选
              </el-radio>
              <el-radio v-model="ruleForm.memberType" :label="3" :disabled="memberTypeTotal>=20&&isAdd">
                会员筛选
              </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"
              @store-change="storeChange"
            />
          </el-form-item>
          <el-form-item v-show="ruleForm.memberType === 3">
            <vue-gic-people
              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>
          <div>
            <el-form-item style="margin-top:50px">
              <el-button
                type="primary"
                size="small"
                @click="submit()"
                :loading="btnLoading"
              >
                确认
              </el-button>
            </el-form-item>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import request from '../../../service/request';
export default {
  data () {
    const activityTimeVal = (rule, value, callback) => {
      callback(new Error('请填写'));
    };
    return {
      breadcrumbTitle: '新建上架规则',
      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,
    };
  },
  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();
    const obj = {
      edit: '编辑上架规则',
      add: '新建上架规则',
      copy: '复制上架规则',
    };
    this.breadcrumbTitle = obj[this.$route.meta.type];
  },
  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 () {
      console.log(this.ruleForm);
      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;
          request.post('/api-integral-mall/add-update-rule', data).then(res => {
            this.$router.go(-1);
          }).finally(() => {
            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>
