<template>
  <el-form :model="formData" label-width="120px" ref="ruleForm" :rules="rules" v-loading="loading" class="pr-4">
    <div class="flex flex-row justify-between">
      <div class="w-full">
        <el-form-item label="支付名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入支付名称" />
        </el-form-item>
        <el-form-item label="收款主体" prop="payee_name">
          <el-input v-model="formData.payee_name" placeholder="请输入收款主体" />
        </el-form-item>
        <el-form-item label="支付商户号" prop="pay_appid">
          <el-input v-model.number="formData.pay_appid" clearable placeholder="请输入支付商户号" />
        </el-form-item>
        <el-form-item label="支付方式" prop="pay_type">
          <el-select class="w-full" v-model="formData.pay_type" clearable filterable placeholder="请选择支付方式">
            <el-option v-for="(item, index) in paymentList" :key="index" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="小程序类型" prop="miniprogram_type">
          <el-select class="w-full" v-model="formData.miniprogram_type" clearable filterable placeholder="请选择小程序类型">
            <el-option v-for="(item, index) in appletType" :key="index" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="公用支付参数" prop="pay_common_params">
          <template #label>
            <div class="flex items-center">
              <span class="mr-1 text-red-600">*</span>公用支付参数
            </div>
          </template>
          <div class="w-full mb-3" v-for="(item, index) in payCommonParamsList" :key="index">
            <el-input style="width:40%;margin-right:6px;" v-model="item.params" clearable placeholder="请输入参数名称" />
            <el-input style="width:40%;margin-right:6px;" v-model="item.value" clearable placeholder="请输入参数值" />
            <el-button type="primary" @click="addParams" :icon="Plus" circle />
            <el-button type="primary" @click="removeParams(index)" :disabled="payCommonParamsList.length == 1"
              :icon="Minus" circle />
          </div>
        </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 {
  Plus,
  Minus
} from '@element-plus/icons-vue';
import type { FormInstance, FormRules } from 'element-plus'
import { managePayConfigAddConfig } from '@/api/iPayment/index'
import { optionsCommonParams } from '@/api/common/index'
const ruleForm = ref<FormInstance>()
import { onMounted, ref } from 'vue';
const props = defineProps({
  primary: Object | null,
});
const formData = ref({})
const rules = reactive({
  pay_type: [{ required: true, message: '请选择支付方式' }],
  miniprogram_type: [{ required: true, message: '请选择小程序类型' }],
  pay_common_params: [
    {
      required: false,
      message: '请输入公用支付参数',
      trigger: 'blur'
    }
  ],
  remark: [
    {
      required: false,
      message: '请输入备注',
      trigger: 'blur'
    }
  ],
  name: [
    {
      required: true,
      message: '请输入支付名称',
      trigger: 'blur'
    }
  ],
  payee_name: [
    {
      required: true,
      message: '请输入收款主体',
      trigger: 'blur'
    }
  ],
  pay_appid: [
    {
      required: true,
      message: '请输入支付商户号',
      trigger: 'blur'
    },
    { pattern: /^[1-9]\d*$/, message: '只能输正整数', trigger: 'blur' }
  ]
});
const loading = ref(false)
const appletType = ref([])
const paymentList = ref([])
const payCommonParamsList = ref([{ params: '', value: '' }])
const addParams = () => {
  if (validateInput()) {
    payCommonParamsList.value.push({ params: '', value: '' })
  }
}
const removeParams = (idx: number) => {
  payCommonParamsList.value.splice(idx, 1);
}

const validateInput = () => {
  for (const item of payCommonParamsList.value) {
    if (!item.params || !item.value) {
      ElMessage.warning('请输入完整公用支付参数的键值对')
      return false;
    }
    if (checkDuplicate(item)) {
      ElMessage.warning(`键 ${item.params} 已存在，请输入一个唯一的键`)
      return false;
    }
  }
  return true;
};

const checkDuplicate = (item) => {
  const count = payCommonParamsList.value.filter(
    (i) => i.params === item.params
  ).length;
  return count > 1;
};

const initType = () => {
  optionsCommonParams().then(res => {
    appletType.value = res.data.miniprogramType
    paymentList.value = res.data.payType
  })
}
const submitForm = (formEl: FormInstance | undefined) => {
  console.log(payCommonParamsList.value, 'test.value,test.value,');
  let pay_common_params = {}
  for (let item of payCommonParamsList.value) {
    pay_common_params[item.params] = item.value
    console.log(item);
  }
  if (!validateInput()) return
  formData.value.pay_common_params = pay_common_params
  console.log(pay_common_params, 'objobj');
  if (!formEl) return;
  formEl
    .validate(valid => {
      if (valid) {
        managePayConfigAddConfig(formData.value).then(res => {
          ElMessage.success(res.message)
          loading.value = false;
          emit('close')
        })
      } else {
        loading.value = false;
      }
    })
    .then(() => { });
}

if (props.primary) {

}

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