<template>
  <div class="card-edit">
    <a-form :model="dataModel" autocomplete="off" @finish="onFinish">
      <a-divider orientation="left">基础信息</a-divider>
      <a-row :gutter="24">
        <a-col :span="8">
          <a-form-item
            label="企业名称"
            :label-col="{ span: 8 }"
            name="companyName"
            :rules="[{ required: true, message: '请输入企业名称!' }]"
          >
            <a-input v-model:value="dataModel.companyName" placeholder=""
                     :class="{'companyNameIpt': operationType == 'add'}"/>
            <a-button v-if="operationType == 'add'" :loading="normalBtnLoading" style="margin-left: 10px"
                      :disabled="!dataModel.companyName"
                      @click="normalFirm">同步信息
            </a-button>
          </a-form-item>
        </a-col>
        <a-col :span="8">

          <a-form-item
            label="统一信用代码"
            :label-col="{ span: 8 }"
            name="companyCode"
            :rules="[{ required: true, message: '请输入统一信用代码!' }]"
          >
            <a-input v-model:value="dataModel.companyCode" placeholder=""/>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item
            label="所属驿站"
            :label-col="{ span: 8 }"
            name="siteID"
            :rules="[{ required: true, message: '请选择所属驿站!' }]"
          >
            <a-select
              ref="select"
              v-model:value="dataModel.siteID"
              v-on:change="siteChange"
              :options="siteList"
              :field-names="{ label: 'siteName', value: 'siteID' }"
            >
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="8">
          <a-form-item
            label="企业办公地址"
            :label-col="{ span: 8 }"
            name="companyAddress"
            :rules="[{ required: true, message: '请输入企业办公地址!' }]"
          >
            <a-textarea v-model:value="dataModel.companyAddress" placeholder="" :rows="4"/>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item
            label="企业联系人"
            :label-col="{ span: 8 }"
            name="userName"
            :rules="[{ required: true, message: '请输入企业联系人!' }]"
          >
            <a-input v-model:value="dataModel.userName" placeholder=""/>
          </a-form-item>
          <a-form-item
            label="企业状态"
            :label-col="{ span: 8 }"
            name="recordStatus"
            :rules="[{ required: true, message: '请选择企业状态!' }]"
          >
            <a-select
              ref="select"
              v-model:value="dataModel.recordStatus"
              :options="companyStatusList"
              :field-names="{ label: 'name', value: 'value' }"
            >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item
            label="企业联系电话"
            :label-col="{ span: 8 }"
            name="userMobile"
            :rules="[{ required: true, message: '请输入企业联系电话!' }]"
          >
            <a-input v-model:value="dataModel.userMobile" placeholder=""/>
          </a-form-item>
          <a-form-item
            label="是否缺工"
            :label-col="{ span: 8 }"
            name="isShortage"
            :rules="[{ required: true, message: '请选择是否缺工!' }]"
          >
            <a-select
              ref="select"
              v-model:value="dataModel.isShortage"
              :options="shortageStatusList"
              :field-names="{ label: 'name', value: 'value' }"
            >
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="8">
          <a-form-item
            label="企业所在经度"
            :label-col="{ span: 8 }"
            name="longitude"
          >
            <a-input v-model:value="dataModel.longitude" placeholder="" :rows="4"/>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item
            label="企业所在纬度"
            :label-col="{ span: 8 }"
            name="latitude"
          >
            <a-input v-model:value="dataModel.latitude" placeholder=""/>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item
            label="企业成立日期"
            :label-col="{ span: 8 }"
            name="establishmentTime"
          >
            <a-date-picker v-model:value="dataModel.establishmentTime" value-format="YYYY-MM-DD"/>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item
            label="注册资本"
            :label-col="{ span: 8 }"
            name="registeredCapital"
          >
            <a-input-number style="width: 100%" v-model:value="dataModel.registeredCapital" addon-after="万元"
                            :controls="false"></a-input-number>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item
            label="注册地址行政区划"
            :label-col="{ span: 8 }"
            name="signInPoliticalArea"
          >
            <a-input v-model:value="dataModel.signInPoliticalArea"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item
            label="所属行业"
            :label-col="{ span: 8 }"
            name="industryID"
          >
            <a-cascader :load-data="loadLevelIndustryList"
                        v-model:value="dataModel.industryName"
                        :options="IndustryList" change-on-select @change="industryChange">
            </a-cascader>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item
            label="所属产业分类"
            :label-col="{ span: 8 }"
            name="estateCategoryID"
          >
            <a-select
              ref="select"
              v-model:value="dataModel.estateCategoryID"
              :options="estateCategoryList"
              :field-names="{ label: 'name', value: 'value' }"
            >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item
            label="企业标签"
            :label-col="{ span: 8 }"
            name="tagID"
          >
            <a-select
              ref="select"
              v-model:value="dataModel.tagID"
              :options="tagList"
              :field-names="{ label: 'name', value: 'value' }"
            >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item
            label="官网网址"
            :label-col="{ span: 8 }"
            name="website"
          >
            <a-input v-model:value="dataModel.website"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item
            label="企业福利"
            :label-col="{ span: 8 }"
            name="bonus"
          >
            <a-textarea v-model:value="dataModel.bonus" placeholder="" :rows="4"/>
          </a-form-item>
        </a-col>
      </a-row>

      <a-divider orientation="left">其他信息</a-divider>
      <a-row>
        <a-col :span="8">
          <a-form-item
            label="法定代表人(负责人)"
            :label-col="{ span: 8 }"
            name="frName"
          >
            <a-input v-model:value="dataModel.frName" placeholder=""/>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item
            label="营业执照有效期"
            :label-col="{ span: 8 }"
            name="validTime"
          >
            <a-radio-group v-model:value="showPicker" name="showPicker">
              <a-radio value="1">至长期</a-radio>
              <a-radio value="2">
                <a-date-picker
                  v-model:value="showDateTime"
                  picker="date"
                  value-format="YYYY-MM-DD"
                />
              </a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item
            label="企业邮箱"
            :label-col="{ span: 8 }"
            name="companyEmail"
          >
            <a-input v-model:value="dataModel.companyEmail" placeholder=""/>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="8">
          <a-form-item
            label="经济类型"
            :label-col="{ span: 8 }"
            name="companyType"
            :rules="[{ required: false, message: '请选择经济类型!' }]"
          >
            <a-select
              ref="select"
              v-model:value="dataModel.companyType"
              :options="companyTypeList"
              :field-names="{ label: 'name', value: 'value' }"
            >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item
            label="所属县区"
            :label-col="{ span: 8 }"
            name="regionCode"
            :rules="[{ required: false, message: '请选择所属县区!' }]"
          >
            <a-select
              ref="select"
              v-model:value="dataModel.regionCode"
              :options="regionList"
              :field-names="{ label: 'name', value: 'code' }"
              @change="regionChange"
            >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item
            label="所属街道"
            :label-col="{ span: 8 }"
            name="streetCode"
            :rules="[{ required: false, message: '请选择所属街道!' }]"
          >
            <a-select
              ref="select"
              v-model:value="dataModel.streetCode"
              :options="streetList"
              :field-names="{ label: 'name', value: 'code' }"
            >
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="8">
          <a-form-item
            label="企业规模"
            :label-col="{ span: 8 }"
            name="companyModel"
            :rules="[{ required: false, message: '请选择企业规模!' }]"
          >
            <a-select
              ref="select"
              v-model:value="dataModel.companyModel"
              :options="companyModelList"
              :field-names="{ label: 'name', value: 'value' }"
            >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item
            label="用工情况(人)"
            :label-col="{ span: 8 }"
            name="workSituation"
            :rules="[{ required: false, message: '请输入用工人数!' }]"
          >
            <a-input v-model:value="dataModel.workSituation" placeholder=""/>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item
            label="参保人数(人)"
            :label-col="{ span: 8 }"
            name="insuredCount"
            :rules="[{ required: false, message: '请输入参保人数!' }]"
          >
            <a-input-number :min="0" style="width: 100%" :controls="false" v-model:value="dataModel.insuredCount"
                            placeholder=""/>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="24">
          <a-form-item label="标签" :label-col="{ span: 2 }" name="listLabel" >
            <a-button style="margin: 0px 5px 5px 0px;color: black;border: 1px solid rgb(217, 217, 217);" v-for="item in dataModel.listLabel">
              {{ item.labelName }}
            </a-button>
            <a-button @click="onSelectModel">
              <plus-circle-outlined/>选择标签
            </a-button>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col class="table-bottom-a1" span="24">
          <a-form-item :label-col="{span:24}" name="businScope" label="经营范围">
            <a-textarea v-model:value="dataModel.businScope" placeholder="经营范围" :rows="4"/>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col class="table-bottom-a1" span="24">
          <a-form-item :label-col="{span:24}" label="企业简介" name="companyDesc">
            <a-textarea v-model:value="dataModel.companyDesc" placeholder="企业简介" :rows="4"/>
          </a-form-item>
        </a-col>
      </a-row>
      <a-divider orientation="left">附件图片上传</a-divider>
      <b-upload-file :fileRefId="dataModel.companyID" :readonly="false" :multiple="true" style="width: 100%;"
                     :setFileList="setFileList" :accept="'.pdf,.png,.jpg'"  ></b-upload-file>
      <a-form-item class="buttom-btns">
        <a-button @click="onClose">取消</a-button>
        <a-button type="primary" html-type="submit">提交</a-button>
      </a-form-item>
    </a-form>
    <select-label ref="refSelectModel" :list-label="dataModel.listLabel" :big-type="1" @selectLabelChecks="selectLabelChecks"></select-label>
  </div>
</template>
<style>
.ant-table-thead th:first-child{width:200px;}
</style>
<script lang="ts">
import {defineComponent, reactive, ref, toRefs} from 'vue';
import {useRouter} from 'vue-router';
import {useTabsViewStore} from '@/store/modules/tabsView';
import type {SelectProps} from 'ant-design-vue';
import BUploadFile from '@/components/file/uploadFile.vue';
import {getRegionCodeList, getStreetCodeList} from "@/api/system/area/index";
import {save, getCompanyById, normalFirmByCompanyName} from '@/api/companyService/company';
import {getSiteByID, getSiteList} from '@/api/baseSettings/siteInfo';
import {getSysDictionaryList} from '@/api/system/dictionary';
import {getInfo} from '@/api/account';
import dayjs from "dayjs";
import {message} from "ant-design-vue";
import {useUserStore} from "@/store/modules/user";
import {get} from "@/api/common";
import SelectLabel from "@/views/baseSettings/label/selectLabel.vue";

interface FormState {
  dataModel: any;
}

export default defineComponent(
  {
    components: {BUploadFile,SelectLabel},
    setup() {
      const userStore = useUserStore();
      const userInfo = ref(userStore.getUserInfo)
      const router = useRouter();
      const isAllowCommit = ref(true);
      const formState = reactive<FormState>({dataModel: {}});
      const siteList = ref<any>([]);
      const tabsViewStore = useTabsViewStore();
      const showPicker = ref('1');
      const showDateTime = ref<any>();
      const fileList = ref();
      const operationType = ref("");
      const normalBtnLoading = ref(false);
      const refSelectModel = ref();
      const setFileList = (files) => {
        fileList.value = files;
      };
      // const showDataPicker = () => {
      //   let toDay = new Date();
      //   showDateTime.value = dayjs(new Date().toLocaleDateString().replaceAll("/", "-"));
      // }
      const companyStatusList = ref<SelectProps['options']>();
      const estateCategoryList = ref<SelectProps['options']>();
      const shortageStatusList = ref<SelectProps['options']>([
        {value: 1, name: '是'},
        {value: 0, name: '否'},
      ]);

      const regionList = ref<SelectProps['options']>();
      const streetList = ref<SelectProps['options']>();
      const companyTypeList = ref<SelectProps['options']>();
      const companyModelList = ref<SelectProps['options']>();
      const IndustryList = ref<SelectProps["options"]>();
      const fullPath = router.currentRoute.value.fullPath;

      const onClose = () => {
        tabsViewStore.closeCurrentTabByPath('/companyService/enterprise/add');
        tabsViewStore.closeCurrentTabByPath('/companyService/enterprise/edit');
        router.push({name: '/companyService/enterprise/index'});
      };

      const getRegionList = async function(){
        const regionResult: any = await getRegionCodeList();
        regionList.value = regionResult;
      }
      const getStreetList = async function(){
        if(formState.dataModel.regionCode){
          const streetResult: any = await getStreetCodeList(formState.dataModel.regionCode);
          streetList.value = streetResult;
        }

      }
      const getAllSites = () => {
        getSiteList({pageIndex:1,pageSize:9999}).then((result :any) => {
          siteList.value = result.list;
        })
      }

      const getCompanyModelList = async function () {
        const data: any = await getSysDictionaryList("CompanyModel");
        companyModelList.value = data;
        // console.log("companyModelList", companyModelList.value);
      }

      const getCompanyTypeList = async function () {
        const data: any = await getSysDictionaryList("CompanyType");
        companyTypeList.value = data;
        // console.log("companyCategoryList", companyCategoryList.value);
      }

      const getCompanyStatusList = async function () {
        const data: any = await getSysDictionaryList("CompanyStatus");
        companyStatusList.value = data;
      }

      const getEstateCategoryList = async function () {
        const data: any = await getSysDictionaryList("CompanyEstateCategory");
        estateCategoryList.value = data;
      }

      const siteChange = async function () {
        const curSiteData: any = await getSiteByID(formState.dataModel.siteID);
        formState.dataModel.regionCode = curSiteData.regionCode;
        formState.dataModel.streetCode = curSiteData.streetCode;
        await getStreetList();
      }


      const regionChange = async function () {
        formState.dataModel.streetCode = null;
        await getStreetList();
      }

      const companyCodeValidate = ()=>{
        const codeReg = /^[0-9A-Z]+$/;
        if(formState.dataModel.companyCode.length != 18 || !codeReg.test(formState.dataModel.companyCode)){
          message.error("输入的信用代码有误！");
          isAllowCommit.value = false;
        }else{
          let aCode;
          let aCodeValue;
          let total = 0;
          const weightedFactors = [1,3,9,27,19,26,16,17,20,29,25,13,8,24,10,30,28];
          const str = '0123456789ABCDEFGHJKLMNPQRTUWXY';
          for(let i =0;i < formState.dataModel.companyCode.length-1;i++){
            aCode = formState.dataModel.companyCode.substring(i,i+1);
            aCodeValue = str.indexOf(aCode);
            total += aCodeValue * weightedFactors[i];
          }
          let logicCheckCode = 31 - total % 31;
          if(logicCheckCode == 31){
            logicCheckCode = 0;
          }
          const Str = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,J,K,L,M,N,P,Q,R,T,U,W,X,Y";
          const Array_Str = Str.split(',');
          const correctCodeStr  = Array_Str[logicCheckCode];
          console.log("正确的校验码是",correctCodeStr);
          const currentCodeStr = formState.dataModel.companyCode.substring(17, 18);
          if (correctCodeStr != currentCodeStr) {
            message.error('输入的统一信用代码无效！');
            isAllowCommit.value = false;
          }
        }
      };

      const inputDataValidate = () =>{
        const mobileReg = /^1[3|4|5|6|7|8|9]\d{9}$/;
        const landlineReg = /[0-9-()（）]{7,18}/;
        if (!mobileReg.test(formState.dataModel.userMobile) && !landlineReg.test(formState.dataModel.userMobile)) {
          message.error("输入的联系电话有误!");
          isAllowCommit.value = false;
        }
        const emailReg = /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/;
        // 这里由于邮箱非必填所以先判断是否填写了邮箱
        if(formState.dataModel.companyEmail!=null&&formState.dataModel.companyEmail.trim()!=''){
          if(!emailReg.test(formState.dataModel.companyEmail)){
            message.error("输入的企业邮箱有误!");
            isAllowCommit.value = false;
          }
        }
      };

      const onFinish = () => {
        isAllowCommit.value = true;
        console.log(showPicker.value);
        if (showPicker.value === '1') {
          formState.dataModel.validDate = '2099-12-31T00:00:00.000+08:00';
        }
        else {
          formState.dataModel.validDate = showDateTime.value;
        };
        companyCodeValidate();
        inputDataValidate();
        console.log("isAllowCommit",isAllowCommit.value);
        if(isAllowCommit.value){
          save(formState.dataModel).then(result => {
            if (result) {
              tabsViewStore.closeCurrentTab(fullPath);
              tabsViewStore.addTabByPath('/companyService/enterprise/index', {reload: 1});
            }
          })
        }
      }

      const getFirstIndustryList = () => {
        get("industry/getFirstIndustryList", null).then(data => {
          IndustryList.value = (data as any[]).map((x) => {
            return {
              label: x.name,
              value: x.code,
              isLeaf: false,
              tag: 'firstLevel'
            }
          });
        });
      }
      const loadLevelIndustryList = (selectedOptions) => {
        let targetOption = selectedOptions[selectedOptions.length - 1];
        if (targetOption) {
          get("industry/getListByParentIndustryID", {parentIndustryID: targetOption.value}).then(data => {
            targetOption.loading = false;
            targetOption.children = (data as any[]).map((x) => {
              return {
                label: x.name,
                value: x.code,
                isLeaf: true,
                tag: 'secondLevel'
              };
            });
          });
          formState.dataModel.hasindustry = false;
        }
      };

      // 职业资格选择变更事件
      function industryChange(value: any, selectedOptions: any) {
        if (value.length >= 2) {
          formState.dataModel.industryID = selectedOptions[1].value;
          formState.dataModel.industryName = selectedOptions[1].label;
        }
      }

      // 同步获取企业信息
      function normalFirm() {
        if (!formState.dataModel.companyName) {
          return;
        }
        normalBtnLoading.value = true
        normalFirmByCompanyName(formState.dataModel.companyName).then((result) => {
          if (result == null) {
            message.info('未查找到企业信息，请检查名称是否正确');
          } else {
            message.info('匹配完毕');
            Object.keys(result).forEach(key => {
              if (result[key] != null) {
                formState.dataModel[key] = result[key];
              }
            })
          }
        }).finally(() => {
          normalBtnLoading.value = false
        })
      }

      const onSelectModel = ()=>{
        refSelectModel.value.show();
      }

      const selectLabelChecks = (list: any)=>{
        formState.dataModel.listLabel = list;
      }

      const loadData = (id: any) => {
        getAllSites();
        getRegionList();
        getCompanyModelList();
        getCompanyTypeList();
        getCompanyStatusList();
        getEstateCategoryList();
        getFirstIndustryList();
        getInfo().then((loginUserInfo:any)=>{
          console.log("userInfo",loginUserInfo.userID);
          getCompanyById(id,loginUserInfo.userID).then(result => {
            formState.dataModel = result;
            // console.log("curDataModel",formState.dataModel);
            showPicker.value = formState.dataModel.validDate == '2099-12-31T00:00:00.000+08:00' ? '1' : '2';
            if (showPicker.value === '1')
              showDateTime.value = dayjs(new Date().toLocaleDateString().replaceAll("/", "-"));
            else
              showDateTime.value = formState.dataModel.validDate;
          })
        });

      };

      return {
        ...toRefs(formState),
        loadData,
        onClose,
        onFinish,
        siteChange,
        showPicker,
        siteList,
        regionList,
        streetList,
        companyTypeList,
        companyModelList,
        companyStatusList,
        showDateTime,
        regionChange,
        setFileList,
        onSelectModel,
        selectLabelChecks,
        refSelectModel,
        shortageStatusList,
        userInfo,
        estateCategoryList,
        getFirstIndustryList,
        industryChange,
        loadLevelIndustryList,
        IndustryList,
        operationType,
        normalFirm,
        normalBtnLoading
      }
    },
    mounted() {
      const id = history.state.params?.id;
      const op = history.state.params?.op;
      if (op == 1) {
        this.operationType = "add"
      }
      if (op == 2) {
        this.operationType = "edit"
      }
      this.loadData(id);
    }
  })
</script>

<style lang="less" scoped>
.companyNameIpt {
  width: 60%;
}
</style>

