<script setup lang="ts">
import { httpBusinesslist } from "/@/api/interest/organize";

import { httpDetail } from "/@/api/serviceParam/storeSet";

import { BusinessQuery, SupplierQuery, AddrQuery, AccountQuery } from "/@/components/BasicForm"
import { computed, onMounted, ref, watch, nextTick } from "vue";
import { useVModel } from "@vueuse/core"
import { useTask } from "/@/hooks/core"

import { options } from "../config/_options"

const initialData = { id: '', unit: '' }

const initialAddr = { province_code: '', city_code: '', area_code: '' }

const emit = defineEmits(['submit', 'update:data'])
const props = withDefaults(defineProps<{ data: any; visible: boolean; disabled: boolean }>(), { data: { spec_name: '', id: '' } })


const addrCode = ref({ ...initialAddr })
const addrsCode = ref({ ...initialAddr })

const supplierQueryRef = ref<InstanceType<typeof SupplierQuery> | null>(null)
const accountQueryRef = ref<InstnaceType<typeof AccountQuery> | null>(null)


const warehouseTask = useTask({ success(data: any) {
  const { 
    companyNo, 
    supplierNo,
    supplierName,
    contactor_name,
    id, 
    name, 
    wsm_type, 
    contactor, 
    mobile, 
    addr, 
    wsm_name, 
    position, 
    wsm_mobile, 
    wsm_addr, 
    addr_code:_addr_code, 
    addrs_code: _addrs_code
  } = (data || {})
  
  addrCode.value = {..._addr_code}
  addrsCode.value = {..._addrs_code}

  nextTick(() => {
    emit('update:data', { 
      id, 
      companyNo, 
      supplierNo,
      name, 
      wsmtype: wsm_type, 
      contactor_id: contactor,
      mobile,
      addr,
      wsm_name,
      position,
      wsm_mobile,
      wsm_addr,
      addr_code: _addr_code.city_code,
      addrs_code: _addrs_code.city_code
    })

    supplierQueryRef.value?.initialData({ name: supplierName })
    accountQueryRef.value?.initialData({ nickname: contactor_name })
  })
}})


const business = ref<any[]>([])
const title = computed(() => data.value.id ? (props.disabled ? '查看仓库' : '编辑仓库') : '添加仓库')
const visible = useVModel(props, 'visible')
const formRef = ref<any | null>(null)
const data = useVModel(props, 'data')

async function requestBusiness() {
  const res = await httpBusinesslist({ size: 100 })
  business.value = res.code === 0 ? res.data.list : []
}

function handleClose() {
  data.value = { ...initialData }
  visible.value = false
}

async function onSubmit() {
  try {
    await formRef.value.validate();
    data.value.addr_code = { ...addrCode.value }
    data.value.addrs_code = { ...addrsCode.value }
    console.log(data.value)
    emit('submit')
  } catch (err) {
    console.log(err);
  }
}

onMounted(requestBusiness)

const rules =  {
        name: [{ required: true, message: '仓库名称不能为空', trigger: 'blur' }],
        position: [{ required: true, message: '联系人职位不能为空', trigger: 'blur' }],
        wsmtype: [{ required: true, message: '请选择仓库类型', trigger: 'change' }],
        companyNo: [{ required: true, message: '业务公司不能为空', trigger: 'change' }],
        supplierNo: [{ required: true, message: '供应商公司', trigger: 'blur' }],
        addr_code: [{ required: true, message: '仓库所在省/市/区', trigger: 'change' }],
        addr: [{ required: true, trigger: 'blur' }],
        contactor_id: [{ required: true, message: '仓库负责人', trigger: 'change' }],
        mobile: [{ required: true, trigger: 'blur' }],
        wsm_name: [
          { required: true, message: '收发货联系人', trigger: 'blur' },
          {
            min: 1,
            max: 20,
            message: '长度在 1 到 20 个字符',
            trigger: 'blur'
          }
        ],
        wsm_mobile: [
          {
            required: true,
            trigger: 'blur'
          }
        ],
        addrs_code: [
          {
            required: true,
            message: '收发货所在省/市/区',
            trigger: 'change'
          }
        ],
        wsm_addr: [
          { required: true, message: '收发货详细地址', trigger: 'blur' },
          {
            min: 1,
            max: 100,
            message: '长度在 1 到 100 个字符',
            trigger: 'blur'
          }
        ]
      }

function handleChangeAddrCode(data: any){
  const { area, city, province } = data.info
  addrCode.value.area_code = area.code
  addrCode.value.city_code = city.code
  addrCode.value.province_code = province.code
}

function handleChangeAddrsCode(data: any){
  const { area, city, province } = data.info
  addrsCode.value.area_code = area.code
  addrsCode.value.city_code = city.code
  addrsCode.value.province_code = province.code
}

watch(() => visible.value, () => {
  const id = data.value.id
  if(id){ 
    warehouseTask.run(httpDetail({ id })) 
  } else {
    emit('update:data', {
      companyNo: '', 
      supplierNo: '',
      name: '', 
      wsmtype: '', 
      contactor_id: '',
      mobile: '',
      addr: '',
      wsm_name: '',
      position: '',
      wsm_mobile: '',
      wsm_addr: '',
      addr_code: '',
      addrs_code: ''
    })
    addrCode.value = {...initialAddr}
    addrsCode.value = {...initialAddr}
  }
}, 
{ immediate: true }
)
</script>


<template>
  <ElDialog v-model="visible" :title="title" center @close="handleClose">
    <ElForm :model="data" :rules="rules" size="small" ref="formRef" :disabled="disabled" label-width="120px" v-loading="warehouseTask.loading">
      <ElRow :gutter="10">
        <ElDivider>仓库信息</ElDivider>
        <ElCol :span="12">
          <ElFormItem label="仓库所在业务公司" prop="companyNo">
            <BusinessQuery v-model="data.companyNo" disabled />
          </ElFormItem>
        </ElCol>

        <ElCol :span="12">
          <ElFormItem label="仓库所在供应商" prop="supplierNo">
            <SupplierQuery ref="supplierQueryRef" v-model="data.supplierNo" :disabled="data.id" />
          </ElFormItem>
        </ElCol>

        <ElCol :span="12">
          <ElFormItem label="仓库名称" prop="name">
            <ElInput v-model="data.name" placeholder="仓库名称" />
          </ElFormItem>
        </ElCol>

        <ElCol :span="12">
          <ElFormItem label="仓库类型" prop="wsmtype">
            <ElSelect style="width: 100%" v-model="data.wsmtype" placeholder="仓库类型"  :disabled="data.id">
              <ElOption v-for="opt in options" :value="opt.value" :label="opt.label" />
            </ElSelect>
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="仓库负责人" prop="contactor_id">
            <AccountQuery v-model="data.contactor_id" style="width: 100%" placeholder="仓库负责人" ref="accountQueryRef" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="负责人电话" prop="mobile">
            <ElInput v-model="data.mobile" placeholder="负责人电话" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="仓库所在省/市/区" prop="addr_code">
            <AddrQuery v-model="data.addr_code" :level="3" placeholder="仓库所在省/市/区" @change="handleChangeAddrCode" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="仓库所在详细地址" prop="addr">
            <ElInput placeholder="仓库所在详细地址" v-model="data.addr" />
          </ElFormItem>
        </ElCol>

        <ElDivider>收发货信息</ElDivider>
        <ElCol :span="8">
          <ElFormItem label="联系人" prop="wsm_name">
            <ElInput placeholder="联系人" v-model="data.wsm_name" />
          </ElFormItem>
        </ElCol>

        <ElCol :span="8">
          <ElFormItem label="职位" prop="position">
            <ElInput placeholder="职位" v-model="data.position" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="8">
          <ElFormItem label="电话" prop="wsm_mobile">
            <ElInput placeholder="电话" v-model="data.wsm_mobile" />
          </ElFormItem>
        </ElCol>

        <ElCol :span="12">
          <ElFormItem label="收发货省/市/区" prop="addrs_code">
            <AddrQuery v-model="data.addrs_code" :level="3" placeholder="收发货省/市/区" @change="handleChangeAddrsCode" />
          </ElFormItem>
        </ElCol>

        <ElCol :span="12">
          <ElFormItem label="收发货详情地址" prop="wsm_addr">
            <ElInput v-model="data.wsm_addr" placeholder="收发货详情地址" />
          </ElFormItem>
        </ElCol>
      </ElRow>

      <div class="flex w-full justify-end">
        <ElButton type="primary" @click="onSubmit">保存</ElButton>
      </div>
    </ElForm>
  </ElDialog>
</template>
