<template>
  <el-dialog :visible.sync="visible" v-bind="modalOptions">
    <el-form ref="formData" :model="formData" :rules="formRules" size="mini" label-suffix=":" label-width="180px">
      <el-form-item label="关联平台组合活动" prop="composeId">
        <el-select v-model="formData.composeId" size="mini" placeholder="请选择关联平台组合活动" filterable>
          <el-option
            v-for="(item, index) in activityList" :key="item.composeId"
            :label="`${item.composeName}（${item.composeId}）`" :value="item.composeId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="活动配置类型" prop="configType">
        <el-select
          v-model="formData.configType" clearable size="mini" placeholder="请选择活动配置类型"
          @change="formData.roleType = formData.ruleId = formData.joinRule = formData.joinMoney = formData.isCardHolder = formData.serverId = []"
        >
          <el-option label="升级活动" :value="1" />
          <el-option label="分佣活动" :value="2" />
          <el-option label="社区活动" :value="3" />
          <el-option label="赠券活动" :value="4" />
          <el-option label="赠金活动" :value="5" />
          <el-option label="商圈订单" :value="6" />
          <el-option label="爆品家具" :value="7" />
          <el-option label="社区订单" :value="8" />
          <el-option label="用户代金券转增" :value="9" />
          <el-option label="商家代金券转赠" :value="10" />
          <el-option label="同城联盟卡" :value="11" />
        </el-select>
      </el-form-item>
      <el-form-item label="分享爆品活动佣金" prop="shareRule">
        <el-select v-model="formData.shareRule" clearable size="mini" placeholder="请选择规则">
          <el-option label="赠送固定金额" :value="1" />
          <el-option label="商品价格比例" :value="2" />
        </el-select>
      </el-form-item>
        <el-form-item label="爆品分配佣金" prop="shareMoney" v-if="formData.shareRule">
        <el-input v-model="formData.shareMoney" placeholder="请输入分享爆品获得固定金额或价格比例" style="width: 250px;">
          <template #append>
            <div v-if="formData.shareRule === 1">元</div>
            <div v-else-if="formData.shareRule === 2">%</div>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="是否参与" prop="joinRole">
        <el-select
          v-model="formData.joinRole" clearable size="mini" placeholder="请选择是否参与"
          @change="formData.roleType = formData.ruleId = formData.joinRule = formData.joinMoney = ''"
        >
          <el-option label="是" :value="1" />
          <el-option label="否" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="[ 1 ].includes(formData.configType) && (formData.joinRole === 1)" label="升级类型"
        prop="roleType"
      >
        <el-select v-model="formData.roleType" clearable size="mini" placeholder="请选择升级类型">
          <el-option label="团长" :value="1" />
          <el-option label="合伙人" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11].includes(formData.configType) && (formData.joinRole === 1)"
        label="关联佣金配置" prop="ruleId"
      >
        <el-select v-model="formData.ruleId" clearable size="mini" placeholder="请选择关联佣金配置" filterable>
          <el-option
            v-for="(item, index) in ruleList" :key="item.ruleId"
            :label="`${item.activityName || '--'}（${item.ruleId}）`" :value="item.ruleId"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="[1, 2, 3, 4, 5, 6, 7].includes(formData.configType) && (formData.joinRole === 1)" label="规则"
        prop="joinRule"
      >
        <el-select v-model="formData.joinRule" clearable size="mini" placeholder="请选择规则">
          <el-option label="固定金额活动" :value="1" />
          <el-option label="商品价格比例" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="[1, 2, 3, 4, 5, 6, 7].includes(formData.configType) && (formData.joinRole === 1) && (formData.joinRule === 1)"
        label="固定分配佣金总额" prop="commissionPrice"
      >
        <el-input v-model="formData.commissionPrice" placeholder="请输入固定分配佣金总额" style="width: 250px;">
          <template #append>
            <div>元</div>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item
        v-if="[1, 2, 3, 4, 5, 6, 7].includes(formData.configType) && (formData.joinRole === 1)" label="参与值"
        prop="joinMoney"
      >
        <el-input v-model="formData.joinMoney" placeholder="请输入商家参与活动金额或价格比例" style="width: 250px;">
          <template #append>
            <div v-if="formData.joinRule === 1">元</div>
            <div v-else-if="formData.joinRule === 2">%</div>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item
        v-if="[ 3 ].includes(formData.configType) && (formData.joinRole === 1)" label="社区服务"
        prop="serverId"
      >
        <el-select
          v-model="formData.serverId" clearable size="mini"
          placeholder="请选择社区服务" filterable multiple
          @change="(e) => (formData.cardBusinessFields = JSON.stringify(communityList.filter(i => formData.serverId.includes(i.id))))"
        >
          <el-option
            v-for="(item, index) in communityList" :key="item.id"
            :label="`${item.serverInfoName || '--'}（${item.id}）`" :value="item.id"
          />
        </el-select>{{ formData.serverId }}
      </el-form-item>
      <el-form-item
        v-if="[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11].includes(formData.configType) && (formData.joinRole === 1)"
        label="是否发送卡包" prop="isCardHolder"
      >
        <el-radio-group v-model="formData.isCardHolder">
          <el-radio :label="true">是</el-radio>
          <el-radio :label="false">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        v-if="[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11].includes(formData.configType) && (formData.joinRole === 1) && formData.isCardHolder"
        label="卡券类型" prop="cardType"
      >
        <el-select v-model="formData.cardType" clearable size="mini" placeholder="请选择卡券类型">
          <el-option label="社区" :value="1" />
          <el-option label="商圈" :value="2" />
          <el-option label="商城" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11].includes(formData.configType) && (formData.joinRole === 1) && formData.isCardHolder"
        label="卡券类型规则" prop="cardRule"
      >
        <el-radio-group v-model="formData.cardRule">
          <el-radio :label="1">满减券</el-radio>
          <el-radio :label="2">折扣券</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        v-if="[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11].includes(formData.configType) && (formData.joinRole === 1) && formData.isCardHolder"
        label="卡包价格规则" prop="cardMoney"
      >
        <el-input v-model="formData.cardMoney" placeholder="请输入卡包价格规则" style="width: 250px;">
          <template #prepend>
            <div v-if="formData.cardRule === 1">减</div>
            <div v-else-if="formData.cardRule === 2">打</div>
          </template>
          <template #append>
            <div v-if="formData.cardRule === 1">元</div>
            <div v-else-if="formData.cardRule === 2">折</div>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item
        v-if="[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11].includes(formData.configType) && (formData.joinRole === 1) && formData.isCardHolder"
        label="卡券发放数量" prop="cardNum"
      >
        <el-input v-model="formData.cardNum" placeholder="请输入卡券发放数量" style="width: 200px;">
          <template #append>
            <div>天</div>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item
        v-if="[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11].includes(formData.configType) && (formData.joinRole === 1) && formData.isCardHolder"
        label="卡券有效期" prop="cardEffectiveTime"
      >
        <el-input v-model="formData.cardEffectiveTime" placeholder="请输入卡券有效期" style="width: 200px;">
          <template #append>
            <div>天</div>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item
        v-if="[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11].includes(formData.configType) && (formData.joinRole === 1) && formData.isCardHolder"
        label="卡券使用范围" prop="cardRange"
      >
        <el-select v-model="formData.cardRange" clearable size="mini" placeholder="请选择卡券使用范围">
          <el-option label="指定" :value="1" />
          <el-option label="全部" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11].includes(formData.configType) && (formData.joinRole === 1) && formData.isCardHolder && (formData.cardRange === 1)"
        label="卡券指定区域" prop="cardRange"
      >
        <el-cascader
          v-model="regionArrDialog" :props="regionProps" size="large" placeholder="请选择区域"
          @change="formData.cardJson = [ ...new Set(regionArrDialog.map(i => i[i.length - 1])) ].join(',')"
        ></el-cascader>
        <div v-if="String(formData.cardJson)">已选ID：{{ formData.cardJson }}</div>
      </el-form-item>
      <!-- && formData.isCardHolder -->
      <el-form-item
        v-if="[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11].includes(formData.configType) && (formData.joinRole === 1)"
        label="业务json字段" prop="cardBusinessFields"
      >
        <el-input
          v-model="formData.cardBusinessFields" maxlength="255" type="textarea" placeholder="请输入封装第三方业务的JSON字符串"
          style="width: 400px;"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button size="mini" @click="handleClose">取 消</el-button>
        <el-button type="primary" size="mini" @click="handleSubmit">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { savePlatformComposeConfig, updatePlatformComposeConfig, getPlatformComposeConfigById, getPlatformComposePage, getCommunityServerInfoList } from '@/api/active/combinationActivities'
import { getAllPlatformBeeRule } from '@/api/commissionAllocation/gradeCommission'
import { getProvinceList, getChildAreaList } from '@/api/address'

export default {
  name: 'EditModal',
  components: {
  },
  data() {
    return {
      modalOptions: {
        closeOnClickModal: false,
        width: '820px',
        title: ''
      },
      visible: false,
      formData: {
        configId: '',
        composeId: '',
        configType: '',
        joinRole: '',
        joinRule: '',
        roleType: '',
        joinMoney: '',
        commissionPrice: '',
        ruleId: '',
        isCardHolder: '',
        cardType: '',
        cardRule: '',
        cardMoney: '',
        cardNum: '',
        cardEffectiveTime: '',
        cardRange: '',
        cardJson: '',
        cardBusinessFields: '',
        serverId: [], // 非后端参数
        shareRule: null, // 分享活动规则
        shareMoney: 0, // 分享的佣金/比例
      },
      formRules: {
        composeId: [
          { required: true, message: '请选择平台组合活动' }
        ],
        configType: [
          { required: true, message: '请选择活动配置类型' }
        ],
        joinMoney: [
          { required: false, message: '请输入参与值' },
          { pattern: /^0(\.\d{0,2})?$|^[1-9]\d*(\.\d{0,2})?$|^0$/, message: '数值有误' }
        ],
        commissionPrice: [
          { required: false, message: '请输入固定分配佣金总额' },
          { pattern: /^0\.\d{0,2}$|^[1-9]\d*\.\d{0,2}$|^[1-9]\d*$/, message: '数值有误' }
        ],
        cardRule: [
          { required: false, message: '请输入卡包价格规则' },
          { pattern: /^0\.\d{0,2}$|^[1-9]\d*\.\d{0,2}$|^[1-9]\d*$/, message: '数值有误' }
        ],
        cardNum: [
          { required: false, message: '请输入卡券发放数量' },
          { pattern: /^(0|[1-9][0-9]*)$/, message: '请输入正整数' }
        ],
        cardEffectiveTime: [
          { required: false, message: '请输入卡券有效期' },
          { pattern: /^(0|[1-9][0-9]*)$/, message: '请输入正整数' }
        ],
        isCardHolder: [ { required: true, message: '请选择是否发送卡包' } ],
        shareRule: [
          { required: true, message: "请配置分享规则", trigger: "blur" },
        ],
      },
      activityList: [],
      ruleList: [],
      communityList: [],
      regionArrDialog: [],
      regionProps: {
        checkStrictly: true,
        multiple: true,
        lazy: true,
        label: 'name',
        value: 'id',
        lazyLoad(node, resolve) {
          const { level, value } = node
          if (level === 0) {
            getProvinceList().then((res) => {
              resolve(res.data)
            })
          } else if (level != 0) {
            getChildAreaList(value).then((res) => {
              resolve(res.data.map((item) => {
                item.leaf = level === 3
                return item
              }))
            })
          }
        }
      }
    }
  },
  methods: {
    handleClose() {
      this.visible = false
    },
    async initList() {
      const res1 = await getPlatformComposePage({ page: 1, pageSize: 9999 })
      this.activityList = res1.data.list
      const res2 = await getAllPlatformBeeRule({ page: 1, pageSize: 9999 })
      this.ruleList = res2.data.list
      const res3 = await getCommunityServerInfoList({ pageNo: 1, pageSize: 9999 })
      this.communityList = res3.data.records
    },
    handleOpen(params = {}) {
      this.modalOptions.title = params.configId ? '编辑组合活动配置' : '添加组合活动配置'
      this.formData = Object.assign(this.$options.data().formData, params, {
        joinMoney: (params.joinRule === 2) && (typeof params.joinMoney === 'number') ? params.joinMoney * 100 : params.joinMoney
      })
      if (this.formData.cardJson) this.regionArrDialog = this.formData.cardJson.split(',').map((i) => [ i ])
      this.visible = true
      this.initList()
      if (params.configId) {
        this.getInfo(params.configId)
      } else {
        this.$refs.formData && this.$refs.formData.resetFields()
      }
    },
    async getInfo(id) {
      const loading = this.$loading({ text: '加载中' })
      try {
        const res = await getPlatformComposeConfigById({ id })
        this.formData = Object.assign(this.$options.data().formData, res.data, {
          configId: res.data.configId || '',
          composeId: res.data.composeId || '',
          configType: res.data.configType || '',
          joinRole: res.data.joinRole || '',
          joinRule: res.data.joinRule || '',
          roleType: res.data.roleType || '',
          joinMoney: (res.data.joinRule === 2) && (typeof res.data.joinMoney === 'number') ? res.data.joinMoney * 100 : res.data.joinMoney,
          commissionPrice: res.data.commissionPrice || '',
          ruleId: res.data.ruleId || '',
          isCardHolder: res.data.isCardHolder,
          cardType: res.data.cardType || '',
          cardRule: res.data.cardRule || '',
          cardMoney: res.data.cardMoney || '',
          cardNum: res.data.cardNum || '',
          cardEffectiveTime: res.data.cardEffectiveTime || '',
          cardRange: res.data.cardRange || '',
          cardJson: res.data.cardJson || '',
          cardBusinessFields: res.data.cardBusinessFields || '',
          shareRule:res.data.shareRule || ''
        })
        if (this.formData.cardJson) this.regionArrDialog = this.formData.cardJson.split(',').map((i) => [ i ])
        this.$nextTick(() => {
          this.$refs.formData && this.$refs.formData.validate()
        })
      } finally {
        loading.close()
      }
    },
    handleSubmit() {
      this.$refs.formData.validate(async (valid) => {
        if (valid) {
          const loading = this.$loading({ text: '加载中' })
          try {
            const { joinRule, joinMoney,shareMoney,shareRule, ...otps } = this.formData
            const params = {
              joinMoney: joinRule === 2 ? joinMoney / 100 : joinMoney,
              shareMoney: shareRule === 2 ? shareMoney / 100 : shareMoney,
              joinRule,
              ...otps
            }
            console.log(params);
            this.formData.configId ? await updatePlatformComposeConfig(params) : await savePlatformComposeConfig(params)
            loading.close()
            this.$message({ message: `${this.formData.configId ? '编辑' : '添加'}成功!`, type: 'success' })
            this.$emit('success')
            this.visible = false
          } catch (e) {
            console.log(e);
            loading.close()
          } finally {
            loading.close()
          }
        } else {
          this.$message({ message: '请输入相关信息', type: 'warning' })
          return false
        }
      })
    }
  }
}
</script>
