<script setup lang="ts">
import { computed, ref , watch,  reactive } from "vue";
import { useVModel } from "@vueuse/core"
import { ElMessage } from "element-plus";
import { AddrQuery } from "/@/components/BasicForm"
import { useRenderIcon } from "/@/components/ReIcon/src/hooks";
import { httpCreate, httpUpdate, httpInfo, httpEnterpriseInfo, httpEnterpriseUpdate, httpEnterpriseCreate } from "/@/api/serviceParam/business";

import { useTask, useTasks } from "/@/hooks/core"

import ContactModal from "./contact-modal.vue"


const initialData = { 
  code: '',
  name: '',
  pid: '',
  id: '',
  kh: '0'
}

const area = ref("")
const emit = defineEmits(['refresh'])

const props = withDefaults(
  defineProps<{ data: any; pid: string; visible: boolean, breadcrumb: any[] }>(),
  { data: {  kh: '0', name: '', pid: '', id: '' } }
)

const title = computed(() => data.value.id ? '编辑企业/组织' : '添加企业/组织')
const visible = useVModel(props, 'visible')
const data = useVModel(props, 'data')

// 组织详情
const organizeTask = useTask({ initialData: {} })

// 企业详情
const enterpriseTask = useTask({ initialData: {}, success(response: any){
  let { member, middle, branch, parentName, companyName, area: areaLabel } = response
  companyName = companyName.split(parentName)[1]
  data.value.customer_member = member
  const isFreedom =  middle === '0' && branch === '0'
  data.value.code = isFreedom ? '' : middle
  area.value = isFreedom ? '0' : ''
  data.value.organizeName = parentName
  data.value.name = companyName
  data.value.branch = branch
  data.value.middle = middle
  data.value.area = areaLabel
} })


function success(){
  visible.value = false
  emit('refresh')
}

const organizeUpdateTask = useTask({ success })
const organizeCreateTask = useTask({ success })
const enterpriseCreateTask = useTask({ success })
const enterpriseUpdateTask = useTask({ success })


const taskState = useTasks(
  organizeCreateTask,
  organizeUpdateTask, 
  enterpriseUpdateTask,
  enterpriseCreateTask
)

const contact= reactive({
  visible: false,
  index: -1,
  data: {}
})

const formRef = ref<any | null>(null)
const rules = { 
  name: [{ required: true,message: '请输入组织名称',trigger: 'blur' }], 
  kh: [{ required: true,message: '请选择组合/企业',trigger: 'blur' }], 
  code: [{ required: true,message: '请选择企业所在地',trigger: 'blur' }], 
}

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

function handleAddrChange(item: any){
  const { info, code, name } = item
  const { province, city } = info
  data.value.code = code
  data.value.area = name
  data.value.branch = province.code
  data.value.middle = city.code
  area.value = ""
}

function handleFreedomAreaChange(){
  data.value.code = ""
  data.value.area = ""
  data.value.middle = ""
  data.value.province_code = ""
}

async function onSubmit(){
  try {
    await formRef.value.validate();
    let parameter:Record<string, any> = {}
    const { id, kh: region, organizeName, name, middle, branch, customer_member } = data.value

    if(region === '0'){
      parameter.pid = props.pid || '0'
      parameter.name = data.value.name || '0'
    }else {
      if(!customer_member || customer_member.length === 0){
        ElMessage.warning('至少添加一条联系方式')
        return
      }
      parameter.parent =  props.pid || '0'
      parameter.companyName =  organizeName + name
      parameter.area = area.value === '0' ? '不限区域' : data.value.area
      parameter.customer_member = customer_member
      parameter.middle = middle
      parameter.branch = branch
    }

    const isCreate = id === undefined || !id
    const isEnterprise = region === '1'
    if(!isCreate) parameter.id = id

    let task:any = null
    let api: any = null
    if(isCreate){
      task = isEnterprise ? enterpriseCreateTask : organizeCreateTask
      api = isEnterprise ? httpEnterpriseCreate :httpCreate
    }else{
      task = isEnterprise ? enterpriseUpdateTask : organizeUpdateTask
      api = isEnterprise ? httpEnterpriseUpdate : httpUpdate
    }

    task.run(api(parameter))
  } catch (err) {
    console.log(err);
  }
}

function handleContactPersonAdd(){
  contact.data = {}
  contact.index = -1
  contact.visible = true
}

function handleContactUpdate(data, index){
  contact.data = {...data}
  contact.index = index
  contact.visible = true
}

function handleUpdateContactPerson(index: number){
  if(!data.value.customer_member) data.value.customer_member = []
  if(index === -1){
    data.value.customer_member.push(contact.data)
  }else{
    data.value.customer_member[index] = contact.data
  }
}

watch(() => visible.value, (visible) => {
  if(!visible) { return }
  if(!props.data.id){ 
    data.value.kh = "0"
    data.value.organizeName = (props.breadcrumb[props.breadcrumb.length - 1])?.name || ''
   } else {
    if(data.value.kh === '0'){
      organizeTask.run(httpInfo({ id: data.value.id }))
    }else {
      enterpriseTask.run(httpEnterpriseInfo({ id: data.value.id, companyNo: data.value.companyNo }))
    }
   }
}, {
  immediate: true
})
</script>


<template>
  <ElDialog v-model="visible" :title="title" center @close="handleClose">
    <ElForm :model="data" :rules="rules" size="small" ref="formRef" v-loading="organizeTask.loading || enterpriseTask.loading">
      <ElRow :gutter="10">
        <ElCol :span="6">
          <ElFormItem prop="kh" label="组织/企业">
            <ElSelect v-model="data.kh" :disabled="!!data.id" style="width: 100%">
              <ElOption value="0" label="组织" />
              <ElOption value="1" label="企业" />
            </ElSelect>
          </ElFormItem>
        </ElCol>

        <ElCol :span="18" v-if="data.kh === '1'">
          <ElFormItem prop="code" label="企业所在区域">
            <div class="flex w-full">
              <ElRadio v-model="area" label="0" @click="handleFreedomAreaChange">不限</ElRadio>
              <AddrQuery v-model="data.code" style="width:100%" @change="handleAddrChange"  />
            </div>
          </ElFormItem>
        </ElCol>
        
        <ElCol v-if="data.kh === '1'" :span="24">
          <ElFormItem   label="企业名称" prop="name">
            <ElInput v-model="data.name" style="width:100%" placeholder="名称">
              <template v-if="pid && pid !== '0'" #prepend>
                {{ data.organizeName }}
              </template>
            </ElInput>
          </ElFormItem>
        </ElCol>

        <ElCol v-else :span="18">
          <ElFormItem label="组织名称" prop="name">
            <ElInput v-model="data.name" style="width:100%" placeholder="名称">
              <template v-if="pid && pid !== '0'" #prepend>
                {{ data.organizeName }}
              </template>
            </ElInput>
          </ElFormItem>
        </ElCol>

        <ElCol :span="24" v-if="data.kh === '1'" class="mb-[10px]">
          <ElTable size="small" border :data="data.customer_member || []">
            <ElTableColumn label="联系人" prop="contactor" />
            <ElTableColumn label="联系电话" prop="commobile" />
            <ElTableColumn label="职位" prop="position" />
            <ElTableColumn label="所在部门" prop="comdepart" />
            <ElTableColumn label="微信号" prop="wxaccount" />
            <ElTableColumn label="qq号" prop="qqaccount" />
            <ElTableColumn label="邮箱" prop="email" />
            <ElTableColumn label="操作">
              <template #header>
                <div class="flex justify-between">
                  <span>操作</span>
                  <ElButton type="primary" link :icon="useRenderIcon('add')" @click="handleContactPersonAdd" />
                </div>
              </template>

              <template #="{ row, $index }">
                <ElButton type="primary" link :icon="useRenderIcon('edit')" @click="handleContactUpdate(row, $index)" />
              </template>
            </ElTableColumn>
          </ElTable>
        </ElCol>
      </ElRow>

      <ContactModal
        v-model:visible="contact.visible"
        v-model:data="contact.data"
        :index="contact.index"
        @submit="handleUpdateContactPerson"
      />

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