<template>
  <div class="container">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="150px" label-position="right">
      <el-form-item label="开通方式">
        <el-radio-group v-model="form.openType">
          <el-radio label="自动开通" value="auto"></el-radio>
          <el-radio label="手动开通" value="manual"></el-radio>
          <el-radio label="付费开通" value="pay"></el-radio>
        </el-radio-group>
      </el-form-item>
      <div v-if="form.openType == 'pay'">
        <el-form-item label="付费金额" prop="payAmount">
          <el-input v-model="form.payAmount" style="width: 300px;" :maxlength="8" placeholder="请输入"
            @input="e => form.payAmount = filterNumberInput(e)"></el-input>
        </el-form-item>
      </div>
      <div v-if="form.openType == 'auto'">
        <el-form-item label="获得佣金条件" prop="inviteCount">
          <div class="column">
            <el-input v-model="form.inviteCount" placeholder="请输入" :maxlength="8" style="width: 300px;"
              @input="e => form.inviteCount = filterNumberInput(e, 0)">
              <template #append>人</template>
            </el-input>
            <div class="tips">邀请达到指定人数才可赚取佣金</div>
          </div>
        </el-form-item>
        <el-form-item label="被邀请人消费有效">
          <div class="center">
            <el-switch v-model="form.inviteConsume" :active-value="1" :inactive-value="0"></el-switch>
            <div class="tips">
              开启后，被邀请人需要成功支付一次订单才计数
            </div>
          </div>
        </el-form-item>
      </div>
      <el-form-item label="分销奖励次数">
        <div class="column">
          <div class="tips">提示:设置限制次数后，分销员只能从每个粉丝获得指定次数的奖励，超过后的充值和消费订单不再奖励(包含退款订单)</div>
          <el-radio-group v-model="isLimitCount" @change="isLimitCountChange">
            <el-radio label="限制" :value="0"></el-radio>
            <el-radio label="不限制" :value="1"></el-radio>
          </el-radio-group>
        </div>
      </el-form-item>
      <el-form-item label="每人奖励" v-if="isLimitCount === 0" prop="rewardCount">
        <el-input v-model="form.rewardCount" placeholder="请输入" style="width: 300px;"
          @input="e => form.rewardCount = filterNumberInput(e, 1)">
          <template #append>次</template>
        </el-input>
      </el-form-item>
      <el-form-item label="结算时长" prop="settlementDay">
        <div class="column">
          <div class="center">
            <el-input placeholder="请输入" v-model="form.settlementDay" style="width: 300px;"
              @input="e => form.settlementDay = filterNumberInput(e, 0)">
              <template #append>天</template>
            </el-input>
            <div class="tips">结算时长：订单完成后，{{ form.settlementDay ? form.settlementDay : 0 }}天后分销到账分销员账号中</div>
          </div>
          <div class="tips">提示：需要分销员自行提现，可直接提现到微信零钱</div>
        </div>
      </el-form-item>
      <div class="title_row">
        分销员等级
      </div>
      <el-form-item label="升级条件" style="margin-top: 14px;" prop="upgradeType">
        <el-radio-group v-model="form.upgradeType" @change="upgradeTypeChange">
          <el-radio label="不自动升级" value="not_upgrade"></el-radio>
          <el-radio label="邀请有效人数" value="invite"></el-radio>
          <el-radio label="消费金额（不含退款）" value="cost"></el-radio>
        </el-radio-group>
      </el-form-item>
      <div class="err_wrap">
        <el-form-item label-width="0" prop="levelConfigList">
          <div class="level_wrap">
            <div class="level_wrap_row" v-for="(item, index) in form.levelConfigList" :key="index">
              <div class="title">
                {{ index + 1 }}级：{{ item.name || '请输入名称' }}
                <div class="del">
                  <el-icon v-if="index > 0" @click="form.levelConfigList.splice(index, 1)">
                    <Delete />
                  </el-icon>
                </div>
              </div>
              <div class="form_wrap">
                <div class="form_wrap_row">
                  <div class="center">
                    <div class="label">
                      <span class="required">*</span>
                      名称
                    </div>
                    <div class="ipt">
                      <el-input v-model="item.name" placeholder="请输入内容" :maxlength="10"
                        style="width: 200px;"></el-input>
                    </div>
                  </div>
                </div>
                <div class="form_wrap_title">
                  <span v-if="form.upgradeType != 'not_upgrade'">升级条件</span>
                </div>
                <div class="form_wrap_row">
                  <div class="column" v-if="form.upgradeType == 'invite'">
                    <div class="center">
                      <div class="label">
                        <span class="required">*</span>有效人数达
                      </div>
                      <div class="ipt">
                        <el-input v-model="item.inviteCount" placeholder="请输入" :disabled="index === 0"
                          style="width: 200px;" @input="e => item.inviteCount = filterNumberInput(e, 0)">
                          <template #append>人</template>
                        </el-input>
                      </div>
                    </div>
                    <div class="tips">有效人数：被邀请人在店铺消费过，即有一笔订单完成</div>
                  </div>
                  <div class="column" v-if="form.upgradeType == 'cost'">
                    <div class="center">
                      <div class="label">
                        <span class="required">*</span>消费金额达
                      </div>
                      <div class="ipt">
                        <el-input v-model="item.costAmount" placeholder="请输入" :disabled="index === 0"
                          style="width: 200px;" @input="e => item.costAmount = filterNumberInput(e)">
                          <template #append>元</template>
                        </el-input>
                      </div>
                    </div>
                    <div class="tips">消费金额：分销员和被邀请人在店铺订单消费总金额（不包含退款）</div>
                  </div>
                </div>
                <div class="form_wrap_row">
                  <div class="column">
                    <div class="center">
                      <div class="label">
                        <span class="required">*</span>分成比例
                      </div>
                      <div class="ipt">
                        <el-input v-model="item.commission" placeholder="请输入" :maxlength="5" style="width: 200px;"
                          @input="e => item.commission = filterNumberInput(e)">
                          <template #append>%</template>
                        </el-input>
                      </div>
                    </div>
                  </div>
                  <!-- <div class="column">
                    <div class="center">
                      <div class="label">订单二级分成</div>
                      <div class="ipt">
                        <el-input v-model="item.levelTwoCommission" placeholder="请输入" :maxlength="5"
                          style="width: 200px;" @input="e => item.levelTwoCommission = filterNumberInput(e)">
                          <template #append>%</template>
                        </el-input>
                      </div>
                    </div>
                    <div class="tips">二级分成不填，则不进行二级分成</div>
                  </div> -->
                </div>
              </div>
            </div>
          </div>
        </el-form-item>
      </div>
      <el-form-item style="margin-top: 24px;">
        <el-button type="primary" @click="addLevelHandle">添加等级</el-button>
      </el-form-item>
      <div class="title_row mt14">未开通页面</div>
      <el-form-item :label-width="0" style="margin-top: 14px;">
        <WangEditor v-model="form.notActivatedPage" />
      </el-form-item>
    </el-form>
    <div class="footer_wrap">
      <div class="btn">
        <el-button size="large" style="width: 100%;" type="primary" :loading="formLoading"
          @click="submintHandle">保存</el-button>
      </div>
      <div class="btn">
        <el-button size="large" style="width: 100%;" @click="router.back()">取消</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { distributionGet, distributionPut } from '@/api/coupon'
import { filterNumberInput } from '@/utils'
import { useRouter } from 'vue-router'

const router = useRouter()

const isLimitCount = ref(0)
function isLimitCountChange(e) {
  console.log(e);
  if (e === 1) {
    form.value.rewardCount = -1
  } else {
    form.value.rewardCount = ''
  }
}

const formRef = ref(null)
const formLoading = ref(false)
const levelConfigListObj = ref({
  name: '', // 名称
  inviteCount: 0, // 有效人数
  costAmount: '', // 消费金额
  commission: '', // 一级分销比例
  levelTwoCommission: '', // 二级分销比例
})
const form = ref({
  id: '',
  openType: 'pay', // pay购买开通 auto自动开通 manual手动开通
  inviteCount: 0, // 邀请条件人数
  inviteConsume: 0, // 被邀请人消费有效 0 1
  payAmount: '', // 购买开通金额
  rewardCount: '', // 每人奖励次数
  settlementDay: '', // n天结算
  upgradeType: 'invite', // not_upgrade不自动升级 invite邀请有效人数 cost消费金额
  notActivatedPage: '', // 未开通页面富文本
  levelConfigList: [{ ...levelConfigListObj.value }]
})
const rules = ref({
  payAmount: [
    {
      required: true,
      message: '请输入付费金额',
      trigger: 'blur'
    }
  ],
  inviteCount: [
    {
      required: true,
      message: '请输入获得佣金条件',
      trigger: 'blur'
    }
  ],
  rewardCount: [
    {
      required: true,
      message: '请输入每人奖励',
      trigger: 'blur'
    }
  ],
  settlementDay: [
    {
      required: true,
      message: '请输入结算时长',
      trigger: 'blur'
    }
  ],
  upgradeType: [
    {
      trigger: 'change',
      validator: (rule, value, callback) => {
        if (form.value.levelConfigList.length == 0) {
          callback(new Error('至少添加一个等级'))
          return
        }
        callback()
      }
    }
  ],
  levelConfigList: [
    {
      trigger: 'change',
      validator: (rule, value, callback) => {
        let tips = '';
        form.value.levelConfigList.forEach((item, index) => {
          if (item.name === '') {
            tips = `请输入${index + 1}级的名称`
            callback(new Error(tips))
            return
          }
          if (item.inviteCount === '' && form.value.upgradeType == 'invite') {
            tips = `请输入${index + 1}级的有效人数`
            callback(new Error(tips))
            return
          }
          if (item.costAmount === '' && form.value.upgradeType == 'cost') {
            tips = `请输入${index + 1}级的消费金额`
            callback(new Error(tips))
            return
          }
          if (item.commission === '' || item.commission == 0) {
            tips = `请输入${index + 1}级的分成比例`
            callback(new Error(tips))
            return
          }
          // if (item.levelTwoCommission !== '' && item.levelTwoCommission <= 0 && item.levelTwoCommission !== null) {
          //   tips = `请输入有效的${index + 1}级订单二级分成`
          //   callback(new Error(tips))
          //   return
          // }
        })
        callback()
      }
    }
  ]
})

// 条件升级切换
function upgradeTypeChange(e) {
  form.value.levelConfigList = []
  addLevelHandle()
  // form.value.levelConfigList = [{ ...levelConfigListObj.value }]
  // if (e == 'not_upgrade') {
  //   form.value.levelConfigList = []
  // } else {
  // }
}

function addLevelHandle() {
  form.value.levelConfigList.push({ ...levelConfigListObj.value })

  console.log('form.value.levelConfigList===', form.value.levelConfigList);


  if (form.value.levelConfigList.length == 1) {
    form.value.levelConfigList[0].inviteCount = 0
    form.value.levelConfigList[0].costAmount = 0
  }
}

// 提交
function submintHandle() {
  console.log(form.value);

  formRef.value.validate(async valid => {
    try {
      if (valid) {
        await distributionPut(form.value)
        ElNotification({
          title: '注意',
          message: '保存成功',
          type: 'success'
        })
      }
    } catch (error) {
      console.log(error);
    }
  })
}

// 配置信息详情
async function distributionGetAjax() {
  try {
    const res = await distributionGet()
    nextTick(() => {
      form.value = { ...res }
      delete form.value.isEnable
      if (form.value.rewardCount == -1) {
        isLimitCount.value = 1
      }
    })
  } catch (error) {
    console.log(error);
  }
}

onMounted(async () => {
  await distributionGetAjax()
  // nextTick(() => {
  //   formRef.value.resetFields()
  // })
})
</script>

<style scoped lang="scss">
.mt14 {
  margin-top: 14px;
}

.container {
  padding-bottom: 100px;
}

.tips {
  white-space: nowrap;
  font-size: 12px;
  color: #999;
}

.column {
  display: flex;
  flex-direction: column;
}

.center {
  display: flex;
  gap: 12px;
  align-items: flex-start;
}

.title_row {
  padding: 14px 20px;
  background-color: #F8F8F8;
  font-size: 16px;
  color: #333;
}

.level_wrap {
  .level_wrap_row {
    display: flex;

    &:not(:last-child) {
      margin-bottom: 24px;
    }

    .title {
      font-size: 14px;
      color: #333;
      width: 150px;
      display: flex;
      justify-content: flex-end;
      padding-right: 10px;
      display: flex;
      // align-items: center;
      gap: 10px;

      .del {
        position: relative;
        top: 2px;
      }
    }

    .form_wrap {
      flex: 1;

      .form_wrap_title {
        height: 20px;
        display: flex;
        align-items: center;
        font-size: 14px;
        color: #333;
        font-weight: bold;
      }

      .form_wrap_row {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        grid-template-rows: repeat(2, auto);
        grid-column-gap: 34px;

        .label {
          width: 120px;
          font-size: 16px;
          color: #666;
        }

        .ipt {
          flex: 1;
        }
      }
    }
  }
}

.footer_wrap {
  --w: 600px;
  width: var(--w);
  padding: 10px 12px;
  position: fixed;
  left: 50%;
  margin-left: calc(var(--w) / 2 * -1);
  bottom: 44px;
  z-index: 999;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: center;
  gap: 14px;

  .btn {
    flex: 1;
  }
}

.err_wrap {
  ::v-deep .el-form-item__error {
    /* 假设输入框左侧有一定间距，调整到与输入框左侧对齐 */
    margin-left: 150px;
  }
}

.required {
  color: var(--el-color-danger);
  font-size: 12px;
  margin-right: 4px;
}
</style>