<template>
  <!-- 背景色覆盖整个页面，并且能够正常滚动内容，同时固定内层内容的位置 -->
  <body style="margin: 0; padding: 0; overflow: auto">
  <!-- 背景色层 -->
  <div class="bg-gray-100" style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; z-index: -1"></div>
  <!-- 内容层 -->
  <div class="flex justify-center" style="position: relative; margin: 20px auto">
    <!-- 卡片盒子 -->
    <div class="w-full max-w-3xl p-6 bg-white rounded-xl shadow-md">
      <a-tabs v-model:activeKey="activeKey" :tabBarGutter="300" centered >
        <a-tab-pane key="1" tab="企业入驻">
          <a-form
              ref="formDateRef"
              :rules="rules"
              :label-col="labelCol"
              :wrapper-col="wrapperCol"
              layout="horizontal"
              :model="formDate"
              @finish="onFinish"
          >
            <a-form-item label="名称" name="name">
              <a-input :allowClear="true" v-model:value="formDate.name" />
            </a-form-item>
            <a-form-item :allowClear="true" label="统一社会编码" name="socialCode">
              <a-input v-model:value="formDate.socialCode"/>
            </a-form-item>
            <a-form-item label="公司性质" name="nature">
              <a-input :allowClear="true" v-model:value="formDate.nature"/>
            </a-form-item>
            <a-form-item label="行政区划"  name="administrativeDivisionCodes">
              <a-cascader
                  v-model:value="formDate.administrativeDivisionCodes"
                  :options="administrativeDivisionTree"
                  :load-data="loadData"
                  :show-search="{ filter }"
                  @change="searchAdministrativeDivisionTree"
                  placeholder="请选择行政区划"
                  change-on-select
              />
             </a-form-item>
            <a-form-item label="营业执照" name="businessLicense">
              <SingleImageFileUpload v-model:value="formDate.businessLicense" ref="fileUpload"></SingleImageFileUpload>
            </a-form-item>
            <a-form-item label="法人名称">
              <a-input :allowClear="true" v-model:value="formDate.legalPersonInfo" />
            </a-form-item>
            <a-form-item label="法人手机号码">
              <a-input :allowClear="true" v-model:value="formDate.telephone" />
            </a-form-item>
            <a-form-item label="详细地址" >
              <a-input :allowClear="true" v-model:value="formDate.address" />
            </a-form-item>
            <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
              <a-button type="primary" html-type="submit" style="width: 100px">确认</a-button>
              <a-button style="width: 100px;margin-left: 10px" @click="resetForm">重置表单</a-button>
            </a-form-item>
          </a-form>
        </a-tab-pane>
        <a-tab-pane key="2" tab="查询企业状态" >
          <a-form
              :label-col="labelCol"
              :wrapper-col="wrapperCol"
              :model="statusDate"
              layout="horizontal">
            <a-form-item label="统一社会编码" name="onlyCode" :rules="[{ required: true, message: '请输入统一社会编码进行查询' }]">
              <a-input  :allowClear="true" v-model:value="statusDate.onlyCode"></a-input>
            </a-form-item>
            <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
              <a-button type="primary" html-type="submit" style="width: 100px" @click="getCheckStatus">确认</a-button>
            </a-form-item>
          </a-form>
        </a-tab-pane></a-tabs>
    </div>
  </div>
  </body>
</template>

<script setup lang="ts">
import {ref, onMounted,createVNode,h} from 'vue';
import type { Rule } from 'ant-design-vue/es/form';
import type { ShowSearchType } from 'ant-design-vue/es/cascader';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import api from "@/axios";
import {CascaderProps, message, Modal} from 'ant-design-vue';
import SingleImageFileUpload from "@/components/upload/SingleImageFileUpload.vue";
import {useRouter} from "vue-router";
import {formDatePort, statusPort} from "@/types/views/enterprise.ts";
const activeKey = ref('1');
const labelCol = { style: { width: '120px' } };
const wrapperCol = { span: 14 };
const administrativeDivisionTree = ref<TreeNodeVo<string>[]>([])
const formDateRef = ref();
const fileUpload = ref()
const router = useRouter()

const formDate = ref<formDatePort>({
  name:'',
  socialCode:'',
  businessLicense:'',
  legalPersonInfo:'',
  telephone:'',
  administrativeDivisionCodes:'',
  address:'',
  nature:''
})
const statusDate  = ref<statusPort>({
  onlyCode:'',
  unitOptType:'SECURITY_UNIT'
})
const rules: Record<string, Rule[]> = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'change' },
  ],
  socialCode:[
    { required: true, message: '请输入社会编码', trigger: 'change' },
  ],
  nature:[
    { required: true, message: '请填写公司性质', trigger: 'change' },
  ],
  businessLicense:[
    { required: true, message: '请上传营业执照', trigger: 'change' },
  ],
  administrativeDivisionCodes:[
    { required: true, message: '请选择行政区划', trigger: 'change' },
  ]
};

// 调用行政区划 1
const DivisionTree = async ()=>{
  const resp =  await api.get<TreeNodeVo<string>[]>('/common/administrativeDivisionByParentCode',{parentCode:'0'})
  administrativeDivisionTree.value = resp.data as TreeNodeVo<string>[]
  
}

const loadData: CascaderProps['loadData'] = async selectedOptions => {
  const targetOption = selectedOptions[selectedOptions.length - 1];
  targetOption.loading = true;
  const resp =  await api.get<TreeNodeVo<string>[]>('/common/administrativeDivisionByParentCode',{parentCode:targetOption.value})
  targetOption.loading = false;
  targetOption.children = [administrativeDivisionTree.value,...resp.data]
};
// 回显数据
const transformData =  (val:any,tree:any)=>{
  for(let i = 0; i< val.length - 1;i++){
    tree.forEach(async(item:any)=>{
      if(item.value === val[i]){
        item.children = []
        let data =  await api.get<TreeNodeVo<string>[]>('/common/administrativeDivisionByParentCode',{parentCode:val[i]})
        item.children = data.data.map((items:any)=>{
          return {
            label:items.label,
            value:items.value
          }
        })
        transformData(val,item.children)
      }
    })
  }
}
// 可以进行搜索行政区划  2
const filter: ShowSearchType['filter'] = (inputValue, path) => {
  return path.some(option => option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1);
};

// 搜索完成时回调
const  searchAdministrativeDivisionTree = (e:Array<string>)=>{
  formDate.value.administrativeDivisionCodes = e as any
}




// 注册企业入驻
const onFinish = async ()=>{
  //校验表单
  await formDateRef.value.validate()
  const legalPersonInfo = {
    name:formDate.value.legalPersonInfo,
    telephone:formDate.value.telephone
  }
  const securityUnitRegisterParams = {
    name:formDate.value.name,
    socialCode:formDate.value.socialCode,
    businessLicense:formDate.value.businessLicense,
    legalPersonInfo:legalPersonInfo,
    nature:formDate.value.nature,
    administrativeDivisionCodes:formDate.value.administrativeDivisionCodes,
    address:formDate.value.address
  }
  const resp = await  api.post('/common/securityUnitRegister',securityUnitRegisterParams)
  message.success(resp.message)
  fileUpload.value.fileDelete()
  await resetForm()
}
// 重置

const  resetForm = async ()=>{
 await formDateRef.value.resetFields()
  formDate.value = {
    name:'',
    socialCode:'',
    businessLicense:'',
    legalPersonInfo:'',
    telephone:'',
    administrativeDivisionCodes:'',
    address:'',
    nature:''
  }
  fileUpload.value.fileDelete()
}

// 查询企业状态
const getCheckStatus = async ()=>{
  const indexCheckStatusParams = {
    onlyCode:statusDate.value.onlyCode,
    unitOptType:statusDate.value.unitOptType
  }
  const resp =  await api.post<dataStatus>('/management/getCheckStatus',indexCheckStatusParams)
  showConfirm(resp.data)
}

const showConfirm = (columnsDate:dataStatus) => {
  if(columnsDate.checkStatus.value === 0){
    Modal.success({
      title: `审核通过`,
      icon: createVNode(ExclamationCircleOutlined),
      content: h('div', {}, [
        h('div', `账号：${columnsDate.account}`),
        h('div', `密码：${columnsDate.password}`),
        h('div', `${columnsDate.remark}`)
      ]),
      okText:'跳转',
      async onOk() {
        await router.push({
          path:'/login',
          query:{
            account:columnsDate.account,
            password:columnsDate.password
          }
        }).then(()=>{})
      },
      onCancel() {},
    });
  }else{
    Modal.error({
      title: `未审核`,
      icon: createVNode(ExclamationCircleOutlined),
      content:`${columnsDate.remark}`,
    });
  }

};
onMounted( async ()=>{
  await  DivisionTree()
  await  transformData(formDate.value.administrativeDivisionCodes,administrativeDivisionTree.value)
})


</script>

