<template>
  <el-form :model="formCallback" label-width="120px" ref="form" v-loading="loading" class="pr-4">
    <el-form-item label="巨量账户ID" prop="account_id" :rules="[{ required: true, message: '巨量账户ID必须填写' }]"
      label-width="120px">
      <el-input v-model.number="formCallback.account_id" type="number" auto-complete="off"
        placeholder="请输入巨量账户ID"></el-input>
    </el-form-item>
    <!-- <el-form-item label="巨量账户名称" prop="account_name" label-width="120px"
      :rules="[{ required: true, message: '巨量账户名称必须填写' }, { max: 20, message: '至多输入20个字符', trigger: 'blur' }]">
      <el-input v-model="formCallback.account_name" auto-complete="off" placeholder="请输入巨量账户名称"></el-input>
    </el-form-item> -->
    <el-form-item label="回传配置" prop="default_rate" :rules="[{ required: true, message: '回传配置必须填写' }]">
      <div class="flex flex-col">
        <el-form-item label="输入回传金额" prop="price">
          <div class="items-center w-full">
            <el-input style="width:200px;margin:0 5px;" v-model.number="formCallback.min_money">
              <template #append>元</template>
            </el-input>
            <span>—</span>
            <el-input style="width:200px;margin:0 5px;" v-model.number="formCallback.max_money">
              <template #append>元</template>
            </el-input>
          </div>
        </el-form-item>
        <el-form-item class="ml-6" label="" label-width="fit-content">
          <span class="small-title">设置回传比例及计划保护数</span>
        </el-form-item>
        <el-form-item label="计划保护数：" prop="protect_num">
          <el-input-number :min="0" type="number" v-model.number="formCallback.protect_num"></el-input-number>
        </el-form-item>
        <el-form-item label="回传比例：" prop="default_per">
          <div>
            <div class="custom-item">
              <div class="custom-line">
                <span>默认回传比例:</span>
                <el-input-number type="number" class="input" v-model.number="formCallback.default_rate" :min="0"
                  :max="100"></el-input-number>&nbsp;%
                <div>
                  未配置的时间段使用默认回传比例
                </div>
              </div>
            </div>
            <div class="custom-item" v-for="(item, index) in formCallback.rate_time_config" :key="index">
              <el-icon class="cursor-pointer el-icon-close closeitem" @click="removeItem(index)">
                <Close />
              </el-icon>
              <div class="custom-line">
                <span>回传比例：</span>
                <el-input-number type="number" class="input" v-model="item.config_per" :min="0"
                  :max="100"></el-input-number>&nbsp;%
              </div>
              <div class="custom-line">
                <span>生效时间：</span>
                <el-time-picker @change="timeChange($event, item)" is-range v-model="item.time" format="HH:mm"
                  range-separator="至" value-format="HH:mm" start-placeholder="开始时间" end-placeholder="结束时间"
                  placeholder="选择时间范围">
                </el-time-picker>
              </div>
            </div>
            <div class="add-btn" style="cursor: pointer;" @click="addBack">
              添加回传比例
            </div>
          </div>
        </el-form-item>
        <el-form-item label="回传开关" prop="state" :rules="[{ required: false, message: '回传开关' }]">
          <el-switch v-model="formCallback.state" :active-value="1" :inactive-value="0"></el-switch>
        </el-form-item>
      </div>
    </el-form-item>
    <div class="flex justify-end">
      <el-button type="primary" @click="submitForm(form)">{{
        $t('system.confirm')
      }}</el-button>
    </div>
  </el-form>
</template>

<script lang="ts" setup>
import { Close } from '@element-plus/icons-vue';
import { FormInstance } from 'element-plus';
import { callbackJuliangAccountAddAccount } from '@/api/backConfig/index'
import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
const route = useRoute()
const emit = defineEmits(['close']);
const loading = ref(false)
const form = ref()
const promotion = ref('')
const formCallback = ref({
  account_id: '',
  account_name: '',
  min_money: 30,
  max_money: null,
  state: 1,
  protect_num: 0,
  default_rate: 0,
  rate_time_config: [],
})

const timeChange = (e, item) => {
  console.log(e, item);
  item.start_time = e[0]
  item.end_time = e[1]
}

// 提交回传配置
const submitForm = (formEl: FormInstance | undefined) => {
  if (!ValiteFunc1()) {
    return
  }
  if (!formEl) return;
  loading.value = true;
  if (!formEl) return;
  formEl
    .validate(valid => {
      if (valid) {
        callbackJuliangAccountAddAccount(formCallback.value).then(res => {
          ElMessage.success(res.message)
          emit('close')
          if (promotion.value) {
            router.push({ path: '/promotion/promotionList', query: { tab: 0 } })
          }
        })
        loading.value = false;
      } else {
        loading.value = false;
      }
    })
    .then(() => { });
}

const ValiteFunc1 = () => {
  let valite = true;
  let dateArr = [];
  formCallback.value.rate_time_config.forEach((item, index) => {
    if (
      item.start_time &&
      item.end_time &&
      item.start_time != item.end_time
    ) {
      console.log(item.start_time, item.end_time, item.start_time != item.end_time);
      dateArr.push({
        start_time: item.start_time,
        end_time: item.end_time
      });
    } else {
      valite = false;
    }
  });
  //时间都填写的情况下，在去判断是否重叠时间
  if (dateArr.length > 0 && formCallback.value.rate_time_config.length == dateArr.length) {
    valite = isHasRepeatTime(dateArr);
  }

  let configBool = formCallback.value.rate_time_config.every(el => {
    return el.config_per && el.end_time && el.start_time
  })

  if (formCallback.value.min_money == null || formCallback.value.max_money == null) {
    ElMessage.error('请输入回传金额')
    valite = false;
  } else if (
    formCallback.value.max_money <=
    formCallback.value.min_money &&
    formCallback.value.max_money
  ) {
    ElMessage.error("回传金额上限小于或等于回传金额下限，请重新输入");
    valite = false;
  } else if (formCallback.value.protect_num == null) {
    ElMessage.error('请输入计划保护数')
    valite = false;
  } else if (formCallback.value.default_rate == null) {
    ElMessage.error('请输入默认回传比例')
    valite = false;
  } else if (!configBool) {
    ElMessage.error('请检查回传比例输入是否完成')
    valite = false;
  } else if (!valite) {
    ElMessage.error('起止时间未选择或起止时间有重叠，请重新排查')
  }
  return valite;
}

const isHasRepeatTime = (dateArr = []) => {
  const startTimeArr = [];
  const endTimeArr = [];
  dateArr.map(item => {
    startTimeArr.push(item.start_time), endTimeArr.push(item.end_time);
  });
  const allStartTime = startTimeArr.sort();
  const allEndTime = endTimeArr.sort();
  let result = 0;
  for (let k = 1; k < allStartTime.length; k++) {
    if (allStartTime[k] <= allEndTime[k - 1]) {
      result += 1;
      break;
    }
  }
  return result <= 0;
}
const removeItem = (idx) => {
  formCallback.value.rate_time_config.splice(idx, 1);
}
const addBack = () => {
  formCallback.value.rate_time_config.push({
    start_time: "",
    end_time: "",
    config_per: 100
  });
}

onMounted(() => {
  promotion.value = route.query?.promotionId
});
</script>

<style lang="scss" scoped>
.custom-item {
  margin: 10px 0;
  background: #f7f7f7;
  padding: 20px;
  width: 600px;
  overflow: hidden;

  .closeitem {
    float: right;
  }

  .custom-line {
    >span {
      padding-right: 15px;
    }

    margin-bottom: 10px;

    &:last-child {
      margin-bottom: 0;
    }
  }
}

.add-btn {
  height: 30px;
  width: 640px;
  text-align: center;
  border: 1px #20a0ff dashed;
  line-height: 30px;
  border-radius: 4px;
  color: #20a0ff;
  margin-bottom: 10px;
}

:deep(.small-title) {
  font-size: 10px;
  color: grey;
}
</style>
