<script setup lang="ts">
import { ref } from "vue"

import {
  taxpayerOptions,
  coopStateoptions,
  sourceOptions,
  applicationTypeOptions,
  categoryOptions,
  deliveryWayOptions,
  supplierTypeOptions,
  supplierLevelOptions,
  payTypeOptions,
  initialData,
  rules
} from "./config/_options"

import { AccountQuery, BusinessTypeQuery } from "/@/components/BasicForm"
import { MultipleImageUpload, ImageSingleUpload } from "/@/components/ImageUpload";
import { httpInfo, httpCreate, httpUpdate } from "/@/api/serviceParam/supplier";
import { useRoute, useRouter } from "vue-router"
import { useTask, useTasks } from "/@/hooks/core"
import { ElForm } from "element-plus"


import { isEncoded, pick } from "/@/utils/global"

const route = useRoute()
const router = useRouter()
const accountQueryRef = ref<InstanceType<typeof AccountQuery> | null>(null)

const success = () => router.push('/supplierSettings/supplier')
const supplierCreateTask = useTask({ success })
const suppierUpdateTask = useTask({ success })
const taskState = useTasks(supplierCreateTask, suppierUpdateTask)

const ruleForm = ref({ ...initialData })
const formRef = ref<InstanceType<typeof ElForm> | null>(null)

const supplierInfoTask = useTask({
  success(data) {
    ruleForm.value = pick(data, Object.keys(initialData), {
      lead_prove:lead_prove => lead_prove || '',
      legaler_type: legaler_type => legaler_type || '',
      prove_img: prove_img => prove_img || [],
      personid: personid => String(personid)
    })

    accountQueryRef.value?.initialData({ nickname: ruleForm.value.person })
  }
})



async function onSubmit() {
  try {
    await formRef.value.validate()
    const isCreate = route.query.type === 'create'
    const parameters = JSON.parse(JSON.stringify(ruleForm.value))

    const task = isCreate ? supplierCreateTask : suppierUpdateTask
    const api = isCreate ? httpCreate : httpUpdate
    
    const encodeProps  = ['prove_img','license_img','lead_prove']


    encodeProps.forEach(prop => {
      let source = prop === 'prove_img' ? parameters[prop].join(',') : parameters[prop]
      if(!isEncoded(source)) source = encodeURI(source) 
      parameters[prop] = source
    })

    if(isCreate) delete parameters['id']
    delete parameters['code']
    task.run(api(parameters))
  } catch (err) {
    console.log(err)
  }
}

route.query.id && supplierInfoTask.run(httpInfo({ code: route.query.id }))
</script>

<template>
  <ElForm label-width="100px" :model="ruleForm" :rules="rules" ref="formRef" v-loading="supplierInfoTask.loading" :disabled="route.query.type === 'preview'">
    <ElRow :gutter="10">
      <ElCol :span="6">
        <h5 class="mb-[10px]" style="border-left:5px solid #006eff;padding-left: 5px">基础信息</h5>
      </ElCol>

      <ElCol :span="6">
        <ElFormItem label="合约状态" prop="coop_state">
          <ElSelect v-model="ruleForm.coop_state" style="width: 100%">
            <ElOption 
              v-for="opt in coopStateoptions" 
              :key="opt.value" 
              :label="opt.label" 
              :value="opt.value" 
            />
          </ElSelect>
        </ElFormItem>
      </ElCol>

      <ElCol :span="6">
        <ElFormItem label="供应商来源" prop="source">
          <ElSelect v-model="ruleForm.source" style="width: 100%">
            <ElOption 
              v-for="opt in sourceOptions" 
              :label="opt.label" 
              :value="opt.value"
              :key="opt.value" 
            />
          </ElSelect>
        </ElFormItem>
      </ElCol>

      <ElCol :span="6">
        <ElFormItem label="申请类型" prop="type">
          <ElSelect v-model="ruleForm.type" style="width: 100%">
            <ElOption 
              v-for="opt in applicationTypeOptions" 
              :key="opt.value" 
              :label="opt.label" 
              :value="opt.value" 
            />
          </ElSelect>
        </ElFormItem>
      </ElCol>

      <ElCol :span="6">
        <ElFormItem 
          label="统一社会信用代码" 
          label-width="130px" 
          prop="invoice_code"
        >
          <ElInput 
            v-model="ruleForm.invoice_code" 
            placeholder="统一社会信用代码" 
          />
        </ElFormItem>
      </ElCol>

      <ElCol :span="6">
        <ElFormItem label="所属类别" prop="category">
          <ElSelect v-model="ruleForm.category" style="width: 100%">
            <ElOption 
              v-for="opt in categoryOptions" 
              :key="opt.value" 
              :label="opt.label" 
              :value="opt.value"
            />
          </ElSelect>
        </ElFormItem>
      </ElCol>

      <ElCol :span="6">
        <ElFormItem label="物流方式" prop="delivery_way">
          <ElSelect v-model="ruleForm.delivery_way" style="width: 100%">
            <ElOption v-for="opt in deliveryWayOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
          </ElSelect>
        </ElFormItem>
      </ElCol>

      <ElCol :span="6">
        <ElFormItem label="供应商类型" prop="supplier_type">
          <ElSelect v-model="ruleForm.supplier_type" style="width: 100%">
            <ElOption 
              v-for="opt in supplierTypeOptions" 
              :label="opt.label" 
              :value="opt.value"
              :key="opt.value" 
            />
          </ElSelect>
        </ElFormItem>
      </ElCol>

      <ElCol :span="6">
        <ElFormItem label="供应商级别" prop="level">
          <ElSelect v-model="ruleForm.level" style="width: 100%">
            <ElOption v-for="opt in supplierLevelOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
          </ElSelect>
        </ElFormItem>
      </ElCol>

      <ElCol :span="6">
        <ElFormItem label="支付方式" prop="pay_type">
          <ElSelect v-model="ruleForm.pay_type" style="width: 100%">
            <ElOption v-for="opt in payTypeOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
          </ElSelect>
        </ElFormItem>
      </ElCol>

      <ElCol :span="9">
        <ElFormItem label="资质证明" prop="prove_img">
          <div class="w-full flex flex-wrap">
            <MultipleImageUpload style="width:100%" v-model="ruleForm.prove_img" />
          </div>
        </ElFormItem>
      </ElCol>
    </ElRow>

    <ElRow>
      <ElCol :span="6">
        <ElFormItem label="纳税人资质" prop="legaler_type">
          <ElSelect v-model="ruleForm.legaler_type"  style="width: 100%" placeholder="纳税人资质">
            <ElOption 
              v-for="opt in taxpayerOptions"
              :key="opt.value"
              :label="opt.label"
              :value="opt.value"
            />
          </ElSelect>
        </ElFormItem>

        <ElFormItem label="负责人" prop="personid">
          <AccountQuery v-model="ruleForm.personid" placeholder="负责人" ref="accountQueryRef" />
        </ElFormItem>
      </ElCol>
      
      <ElCol :span="6">
        <ElFormItem label="纳税人资质证明" prop="lead_prove" label-width="120px">
          <ImageSingleUpload style="width:100%" v-model="ruleForm.lead_prove" />
        </ElFormItem>
      </ElCol>

      <ElCol :span="6">
        <ElFormItem label="营业执照" prop="license_img">
          <ImageSingleUpload style="width:100%" v-model="ruleForm.license_img" />
        </ElFormItem>
      </ElCol>
    </ElRow>

    <ElRow>
      <ElCol :span="24">
        <h5 class="mb-[10px]" style="border-left:5px solid #006eff;padding-left: 5px">
          联系人信息
        </h5>
      </ElCol>

      <ElCol :span="8">
        <ElFormItem label="姓名" prop="contactor">
          <ElInput v-model="ruleForm.contactor" placeholder="姓名" />
        </ElFormItem>
      </ElCol>

      <ElCol :span="8">
        <ElFormItem label="手机号" prop="mobile">
          <ElInput v-model="ruleForm.mobile" maxlength="20" placeholder="手机号" />
        </ElFormItem>
      </ElCol>

      <ElCol :span="8">
        <ElFormItem label="电子邮箱" prop="email">
          <ElInput v-model="ruleForm.email" maxlength="50" placeholder="电子邮箱" />
        </ElFormItem>
      </ElCol>

      <ElCol :span="8">
        <ElFormItem label="职位" prop="position">
          <ElInput v-model="ruleForm.position" maxlength="50" placeholder="职位" />
        </ElFormItem>
      </ElCol>

      <ElCol :span="8">
        <ElFormItem label="座机号" prop="telephone">
          <ElInput v-model="ruleForm.telephone" maxlength="50" placeholder="座机号" />
        </ElFormItem>
      </ElCol>
    </ElRow>

    <ElRow>
      <ElCol :span="24">
        <h5 class="mb-[10px]" style="border-left:5px solid #006eff;padding-left: 5px">营业执照信息</h5>
      </ElCol>

      <ElCol :span="16">
        <ElFormItem label="供应商名称" prop="name">
          <ElInput v-model="ruleForm.name" maxlength="50" placeholder="供应商名称" />
        </ElFormItem>
      </ElCol>

      <ElCol :span="8"  v-if="route.query.type === 'create' ? !ruleForm.license_img  : true">
        <ElFormItem label="统一社会信用代码" prop="registercode" label-width="140px">
          <ElInput v-model="ruleForm.registercode" maxlength="50" placeholder="统一社会信用代码" />
        </ElFormItem>
      </ElCol>

      <ElCol :span="8"   v-if="route.query.type === 'create' ? !ruleForm.license_img  : true">
        <ElFormItem label="公司类型" prop="nature">
          <BusinessTypeQuery v-model="ruleForm.nature" maxlength="50" placeholder="公司类型" />
        </ElFormItem>
      </ElCol>

      <ElCol :span="8"  v-if="route.query.type === 'create' ? !ruleForm.license_img  : true">
        <ElFormItem label="法人代表" prop="legaler">
          <ElInput v-model="ruleForm.legaler" placeholder="法人代表" maxlength="20" />
        </ElFormItem>
      </ElCol>

      <ElCol :span="8"   v-if="route.query.type === 'create' ? !ruleForm.license_img  : true">
        <ElFormItem label="成立日期" prop="registertime">
          <ElInput v-model="ruleForm.registertime" maxlength="50" placeholder="成立日期" />
        </ElFormItem>
      </ElCol>

      <ElCol :span="24"  v-if="route.query.type === 'create' ? !ruleForm.license_img  : true">
        <ElFormItem label="详细地址" prop="addr">
          <ElInput v-model="ruleForm.addr" maxlength="200" placeholder="详细地址" />
        </ElFormItem>
      </ElCol>

      <ElCol :span="24"  v-if="route.query.type === 'create' ? !ruleForm.license_img  : true">
        <ElFormItem label="运营范围" prop="scope">
          <ElInput type="textarea" v-model="ruleForm.scope" maxlength="5000" placeholder="运营范围" show-word-limit />
        </ElFormItem>
      </ElCol>

      <ElCol :span="24">
        <div class="flex w-full justify-end">
          <ElButton @click="onSubmit" type="primary" :loading="taskState.loading">保 存</ElButton>
        </div>
      </ElCol>
    </ElRow>
  </ElForm>
</template>
