<template>
  <el-form :model="formData" label-width="120px" ref="ruleForm" :rules="rules" class="pr-4">
    <div class="flex flex-row justify-between">
      <div class="w-full">
        <el-form-item label="位置" prop="sequenceObj">
          <el-select class="w-full" v-model="formData.sequenceObj" @change="sequenceChange" value-key="sequence"
            filterable clearable placeholder="请选择位置">
            <el-option v-for="(item, index) in optionSequence" :key="index" :label="item.sequence_text" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="档位类型" prop="typeObj">
          <el-select class="w-full" v-model="formData.typeObj" value-key="type" filterable clearable
            placeholder="请选择档位类型">
            <el-option v-for="(item, index) in optionTypeList" :key="index" :label="item.type_name" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <div class="items-center w-full">
            <span>充</span>
            <el-input style="width:200px;margin:0 5px;" v-model="formData.price" placeholder="请输入金额">
              <template #append>元</template>
            </el-input>
          </div>
        </el-form-item>
        <el-form-item prop="given" v-if="!isShowBi" style="margin-bottom:0px;">
          <div class="items-center w-full">
            <span>送</span>
            <el-input style="width:200px;margin:0 5px;" v-model="formData.given" placeholder="请输入充送看币">
              <template #append>币</template>
            </el-input>
          </div>
        </el-form-item>
        <el-form-item v-if="!isShowBi">
          <div class="mt-4 text-sm text-gray-400">1元=100k币，充送看币不能超过当前价格的3倍</div>
        </el-form-item>
        <el-form-item label="默认项" prop="is_default">
          <el-select class="mr-2 w-300" v-model="formData.is_default" @change="defaultChange" filterable clearable
            placeholder="请选择默认项">
            <el-option label="默认项" :value="1" />
            <el-option label="非默认项" :value="0" />
          </el-select>
          <el-tooltip placement="top">
            <template #content> 默认选中的充值档位 </template>
            <el-icon>
              <InfoFilled />
            </el-icon>
          </el-tooltip>
        </el-form-item>
      </div>
    </div>
    <div class="flex justify-end">
      <el-button type="primary" @click="submitForm(ruleForm)">{{ $t('system.confirm') }}</el-button>
    </div>
  </el-form>
</template>

<script lang="ts" setup>
import { InfoFilled } from '@element-plus/icons-vue';
import type { FormInstance, FormRules } from 'element-plus'
import {
  channelPaytemplateOptionTypeList,
  channelPaytemplateOptionOptionSequence
} from '@/api/charge/index'
const ruleForm = ref<FormInstance>()
const props = defineProps({
  primary: String | Number,
  data: Array
});

const filtersObj = ['MONTH', 'QUARTER', 'YEAR']

const isShowBi = computed(() => filtersObj.includes(formData.value?.typeObj?.type))
const optionTypeList = ref([]);
const optionSequence = ref([])
const formData = ref({})
const rules = reactive({
  price: [
    {
      required: true,
      message: '请输入金额',
      trigger: 'blur'
    },
    { pattern: /^\d+(\.\d{1,2})?$/, message: '金额最多只能有两位小数', trigger: 'blur' },
    { pattern: /^(?!0\d+)\d+(\.\d+)?$/, message: '请输入有效的金额', trigger: 'blur' },
  ],
  given: [
    {
      required: true,
      message: '请输入充送看币',
      trigger: 'blur'
    },
    { pattern: /^[1-9]\d*$/, message: '请输入正整数充送看币', trigger: 'blur' },
  ],
  sequenceObj: [
    {
      required: true,
      message: '请选择位置',
      trigger: 'change'
    }
  ],
  typeObj: [
    {
      required: true,
      message: '请选择档位类型',
      trigger: 'change'
    }
  ],

  is_default: [
    {
      required: true,
      message: '请选择默认项',
      trigger: 'change'
    }
  ],
});
const init = () => {
  channelPaytemplateOptionTypeList().then(res => {
    optionTypeList.value = res.data

  })
  channelPaytemplateOptionOptionSequence().then(res => {
    optionSequence.value = res.data
  })
}

const sequenceChange = (e) => {
  const findSequence = props.data.find(el => el.sequence == e.sequence)
  if (findSequence?.sequence_text) {
    ElMessage.error(`${findSequence.sequence_text},已存在请重新选择`)
    const timer = setTimeout(() => {
      formData.value.sequenceObj = ''
      clearTimeout(timer)
    }, 300)
  }
}


const defaultChange = (e) => {
  console.log(e, 'defaultChange', props.data);
}

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl
    .validate(valid => {
      if (valid) {
        if (!formData.value.given) {
          formData.value.given = 0
        }
        const findSequence = props.data.find(el => el.is_default == 1)
        if (findSequence?.sequence_text && formData.value.is_default == 1) {
          ElMessageBox.confirm(
            `当前默认项为${findSequence.sequence_text}，确定要更改吗?`,
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            }
          )
            .then(() => {
              findSequence.is_default = 0
              emit('success', formData.value)
              emit('close')
            })
            .catch(() => {

            })
        } else {
          emit('success', formData.value)
          emit('close')
        }



      } else {
      }
    })
    .then(() => { });
}

if (props.primary) {
  formData.value = JSON.parse(JSON.stringify(props.primary))
  formData.value.sequenceObj = { sequence_text: props.primary.sequence_text, sequence: props.primary.sequence }
  formData.value.typeObj = { type_name: props.primary.type_name, type: props.primary.type }
}

const emit = defineEmits(['close', 'success']);
onMounted(() => {
  init()
});
</script>

<style lang="scss" scoped>
:deep(.form-item) {
  display: inline-table;
  width: 30%;
}

:deep(.form-item-price) {
  flex-wrap: nowrap;
}
</style>
