<script lang="ts" setup>
import { ref, shallowRef , computed , watch, nextTick } from "vue"
import { httpUpdate, httpCreate } from "/@/api/serviceParam/supplierBankDetail";
import { SupplierQuery } from "/@/components/BasicForm"
import { useTask, useTasks } from "/@/hooks/core"
import { useVModel } from "@vueuse/core"
import { ElForm, ElMessage } from "element-plus"

import { contactOptions, rules } from "./../config/_options"

const props = defineProps<{ visible: boolean, data: any, type: string }>()
const emit = defineEmits(['refresh'])
const ruleRef = ref(rules)

const title = computed(() => {
  const mapPrefix = { create: '添加', preview: '查看', update: '编辑' }
  return mapPrefix[props.type || 'create'] + '供应商银行信息'
})

const formRef = ref<InstanceType<typeof ElForm> | null>(null)
const supplierQueryRef = ref<InstanceType<typeof SupplierQuery> | null>(null)

function success(){
  ElMessage.success('操作成功')
  visible.value = false
  emit('refresh')
}

const bankCreateTask = useTask({ success })
const bankUpdateTask = useTask({ success })
const bankState = useTasks(bankCreateTask, bankUpdateTask)
const visible = useVModel(props,'visible')
const data = useVModel(props, 'data')
const contactType = shallowRef('0')

async function onSubmit() {
  try {
    await formRef.value?.validate()
    const { code, bank_name, bank_no, contact_name, contact_mobile, id } = data.value
    const parameter = {  code, bank_name, bank_no, contact_name, contact_mobile, id}
    const isCreate = props.type === 'create'
    if(isCreate) delete parameter.id
    const task = isCreate ? bankCreateTask : bankUpdateTask
    const api = isCreate ? httpCreate : httpUpdate
    task.run(api(parameter))
  } catch (err) {
    console.log(err);
  }
}


watch(() => visible.value, () => {
  if(!visible.value) { return }
  if(props.type === 'create') { return }
  const index = contactOptions.findIndex(({ rule }) => rule.validator(undefined, data.value.contact_mobile))
  nextTick(() =>  supplierQueryRef.value?.initialData({ name: data.value.name }))
  contactType.value = index >= 0 ? String(index) : '0'
})

watch(() => contactType.value, () => {
  ruleRef.value.contact_mobile[0].validator = contactOptions[contactType.value].rule.validator
  nextTick(() => formRef.value?.validateField('contact_mobile'))
})
</script>


<template>
  <ElDialog v-model="visible" :title="title" center>
    <ElForm ref="formRef" :model="data" label-width="100px" :rules="ruleRef" :disabled="type === 'preview'">
      <ElFormItem label="供应商编号" prop="code">
        <SupplierQuery placeholder="供应商编号" ref="supplierQueryRef" v-model="data.code" />
      </ElFormItem>

      <ElFormItem label="开户银行" prop="bank_name">
        <ElInput  v-model="data.bank_name" placeholder="开户银行" />
      </ElFormItem>

      <ElFormItem label="银行卡号" prop="bank_no">
        <ElInput v-model="data.bank_no" placeholder="银行卡号" />
      </ElFormItem>

      <ElFormItem label="联系人" prop="contact_name">
        <ElInput v-model="data.contact_name" placeholder="联系人" />
      </ElFormItem>

      <ElFormItem label="联系电话" prop="contact_mobile">
        <ElInput v-model="data.contact_mobile">
          <template #prepend>
            <ElSelect style="width: 115px" v-model="contactType" placeholder="联系电话">
              <ElOption 
                v-for="contact in contactOptions" 
                :label="contact.label" 
                :value="contact.value"
                :key="contact.value" 
              />
            </ElSelect>
          </template>
        </ElInput>
      </ElFormItem>
    </ElForm>

    <div class="flex justify-end">
      <ElButton type="primary" :loading="bankState.loading" @click="onSubmit">
        保存
      </ElButton>
    </div>
  </ElDialog>
</template>
