<template>
  <el-dialog v-model="visible" :title="title" :before-close="fnClose">
    <el-form
      ref="formRef"
      :rules="rules"
      label-width="220px"
      :model="form"
      label-position="right"
    >
      <el-divider content-position="left">企业基础信息</el-divider>
      <el-row :gutter="24">
        <form-items-renderer v-model="form" :options="baseInfoOptions">
          <template #area>
            <el-cascader
              v-model="form.area"
              :options="dictionariesList"
              :props="{
                value: 'name',
                label: 'name',
                children: 'list',
              }"
            ></el-cascader>
          </template>
          <template #sectorId>
            <app-cascader
              ref="sectorIdRef"
              id="f2598ba72e864eadabf0ca4b664d26b9"
              value="dictionaryId"
              v-model="form.sectorId"
              :check-strictly="false"
            ></app-cascader>
          </template>
          <template #address>
            <el-input v-model="form.address" disabled>
              <template #append
                ><el-button type="primary" @click="handleMap"
                  >定位</el-button
                ></template
              ></el-input
            >
          </template>
        </form-items-renderer>
      </el-row>
      <el-divider content-position="left">企业属性信息</el-divider>
      <el-row :gutter="24">
        <form-items-renderer v-model="form" :options="companyPropsOptions">
        </form-items-renderer>
      </el-row>
    </el-form>
    <el-divider content-position="left">对接上级平台信息</el-divider>
    <div class="add-btn mb-10">
      <el-button type="primary" @click="fnAddThirdList()"
        >添加上级平台</el-button
      >
    </div>
    <el-form ref="formRef1" label-width="220px" label-position="right">
      <el-row :gutter="24" v-for="(item, index) in thirdList" :key="index">
        <el-divider></el-divider>
        <el-col :span="12">
          <el-form-item label="上级对接平台">
            <el-select
              :disabled="thirdListOptions.length === 0"
              v-model="item.thirdPlatformId"
              placeholder="请选择"
            >
              <el-option
                v-for="item1 in thirdListOptions"
                :key="item1.id"
                :label="item1.platformName"
                :value="item1.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="上级平台编码" prop="thirdPlatformCode">
            <el-input v-model="item.thirdPlatformCode"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="重大危险源编码" prop="majorHazardCode">
            <el-input v-model="item.majorHazardCode"> </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="密钥" prop="accessKey">
            <el-input v-model="item.accessKey"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="公钥" prop="rsaPublicKey">
            <el-input v-model="item.rsaPublicKey"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="对接URL" prop="url">
            <el-input v-model="item.url"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="对接IV" prop="iv">
            <el-input v-model="item.iv"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="企业CODE" prop="code">
            <el-input v-model="item.code"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="企业APPID" prop="appid">
            <el-input v-model="item.appid"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="企业SECRET" prop="secret">
            <el-input v-model="item.secret"></el-input>
          </el-form-item>
        </el-col>
        <el-col class="add-btn" :span="24" v-if="index > 0"
          ><el-button type="danger" @click="fnReduceThirdList(index)"
            >删除</el-button
          ></el-col
        >
      </el-row>
    </el-form>

    <template #footer>
      <el-button type="primary" @click="fnSubmit">提交</el-button>
      <el-button @click="fnClose">取消</el-button>
    </template>
  </el-dialog>
  <app-map
    v-model:visible="visibleMap"
    v-model:longitude="form.longitude"
    v-model:latitude="form.latitude"
    @submit="fnSubmitMap"
  ></app-map>
</template>

<script setup>
import useForm from "@/hooks/useForm.js";
import { ref, watch } from "vue";
import { debounce } from "throttle-debounce";
import { ElMessage } from "element-plus";
import FormItemsRenderer from "@/components/form_builder/form_items_renderer.vue";
import {
  setBusCompanyInfoAdd,
  setBusCompanyInfoUpdate,
  getBusCompanyInfo,
  getBusServicePlatformListAll,
} from "@/request/database.js";
import { STATUS_LIST, WHETHER_LIST } from "@/assets/js/constant.js";
import { getAreaListTree } from "@/request/data_dictionary.js";
import AppCascader from "@/components/cascader/index.vue";
import AppMap from "@/components/map/map.vue";
import { UNIFIED_SOCIAL_CREDIT_CODE } from "@/assets/js/regular.js";
const { dictionariesList } = await getAreaListTree();
const visible = defineModel("visible", { type: Boolean, required: true });
const props = defineProps({
  corpInfoId: { type: Number, required: false },
  title: { type: String, required: true },
});
const { data: servicePlatformList } = await getBusServicePlatformListAll();
const emits = defineEmits(["getData"]);
const { formRef, validate, reset } = useForm();
// const { formRef, reset } = useForm();
const form = ref({
  companyName: "", // 企业名称
  code: "", // 统一社会信用代码
  area: [], // 属地
  sectorId: [], // 所属行业
  address: "",
  latitude: "", // 经营地址
  longitude: "", // 经营地址
  companyStatus: "", // 企业状态
  companyAddress: "", // 地理位置
  companyContacts: "", // 主要负责人
  companyMobile: "", // 负责人电话
  servicePlatformId: "", // 服务平台
  isMajorHazard: 0, // 是否重大危险源企业
  isOpenMajorHazard: 0, // 是否开启重大危险源数据推送
  isKeyProcess: 0, // 是否重点工艺企业
  isOpenKeyProcess: 0, // 是否开启重点工艺企业数据推送
  isSpecialInspection: 0, // 是否重点专项检查企业
  isOpenSpecialInspection: 0, // 是否开启重点专项检查企业数据推送
  isDustExplosion: 0, // 是否粉尘涉爆企业
});

const rules = {
  companyName: [
    { required: true, message: "企业名称不能为空", trigger: "blur" },
  ],
  code: [
    { required: true, message: "统一社会信用代码不能为空", trigger: "blur" },

    {
      pattern: UNIFIED_SOCIAL_CREDIT_CODE,
      message: "请输入正确的统一社会信用代码",
    },
  ],
  sectorId: [
    { required: true, message: "所属行业不能为空", trigger: "change" },
  ],
  companyStatus: [
    { required: true, message: "企业状态不能为空", trigger: "change" },
  ],
  companyContacts: [
    { required: true, message: "主要负责人不能为空", trigger: "blur" },
  ],
  companyMobile: [
    { required: true, message: "负责人电话", trigger: "blur" },
    { min: 11, max: 13, message: "请输入手机号码或座机号", trigger: "blur" },
    {
      pattern:
        /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$|^0\d{2,3}-?\d{7,8}$/,
      message: "请输入正确的手机号码或座机号(例:010-12345678)",
    },
  ],
  servicePlatformId: [
    { required: true, message: "服务平台不能为空", trigger: "change" },
  ],
  isMajorHazard: [
    { required: true, message: "是否重大危险源企业", trigger: "change" },
  ],
  isOpenMajorHazard: [
    {
      required: true,
      message: "是否开启重大危险源数据推送",
      trigger: "change",
    },
  ],
  isKeyProcess: [
    { required: true, message: "是否重点工艺企业", trigger: "change" },
  ],
  isOpenKeyProcess: [
    {
      required: true,
      message: "是否开启重点工艺企业数据推送",
      trigger: "change",
    },
  ],
  isSpecialInspection: [
    { required: true, message: "是否重点专项检查企业", trigger: "change" },
  ],
  isOpenSpecialInspection: [
    {
      required: true,
      message: "是否开启重点专项检查企业数据推送",
      trigger: "change",
    },
  ],
  isDustExplosion: [
    { required: true, message: "是否粉尘涉爆企业", trigger: "change" },
  ],
};

const baseInfoOptions = [
  { key: "companyName", label: "企业名称" },
  { key: "code", label: "统一社会信用代码" },
  { key: "area", label: "属地" },
  { key: "sectorId", label: "所属行业" },
  { key: "address", label: "经营地址" },
  {
    key: "companyStatus",
    label: "企业状态",
    type: "select",
    options: STATUS_LIST,
  },
  { key: "companyAddress", label: "地理位置" },
  { key: "companyContacts", label: "主要负责人" },
  { key: "companyMobile", label: "负责人电话" },
  {
    key: "servicePlatformId",
    label: "服务平台",
    type: "select",
    valueKey: "id",
    labelKey: "serviceName",
    options: servicePlatformList,
  },
];

const companyPropsOptions = [
  {
    key: "isMajorHazard",
    label: "是否重大危险源企业",
    type: "radio",
    options: WHETHER_LIST,
  },
  {
    key: "isOpenMajorHazard",
    label: "是否开启重大危险源数据推送",
    type: "radio",
    options: WHETHER_LIST,
  },
  {
    key: "isKeyProcess",
    label: "是否重点工艺企业",
    type: "radio",
    options: WHETHER_LIST,
  },
  {
    key: "isOpenKeyProcess",
    label: "是否开启重点工艺企业数据推送",
    type: "radio",
    options: WHETHER_LIST,
  },
  {
    key: "isSpecialInspection",
    label: "是否重点专项检查企业",
    type: "radio",
    options: WHETHER_LIST,
  },
  {
    key: "isOpenSpecialInspection",
    label: "是否开启专项检查数据推送",
    type: "radio",
    options: WHETHER_LIST,
  },
  {
    key: "isDustExplosion",
    label: "是否粉尘涉爆企业",
    type: "radio",
    options: WHETHER_LIST,
  },
];
const thirdListOptions = ref([]);
watch(
  () => form.value.servicePlatformId,
  (val) => {
    thirdListOptions.value = servicePlatformList.filter(
      (item) => item.id === val
    )[0].thirdList;
  }
);
const fnGetData = async () => {
  if (!props.corpInfoId) return;
  const { data } = await getBusCompanyInfo({ id: props.corpInfoId });
  form.value = data;
  if (form.value.province) {
    form.value.area = [form.value.province, form.value.city, form.value.county];
  }
  form.value.sectorId = data.sectorId.split(",");
  if (form.value.longitude) {
    form.value.address = `${form.value.longitude}-${form.value.latitude}`;
  }
  thirdList.value = data.thirdList;
};

fnGetData();

const fnClose = () => {
  reset();
  visible.value = false;
};
const thirdList = ref([
  {
    thirdPlatformId: "",
    thirdPlatformCode: "",
    majorHazardCode: "",
    accessKey: "",
    rsaPublicKey: "",
    url: "",
    iv: "",
    code: "",
    appid: "",
    secret: "",
  },
]);
const fnAddThirdList = () => {
  thirdList.value.push({
    thirdPlatformId: "",
    thirdPlatformCode: "",
    majorHazardCode: "",
    accessKey: "",
    rsaPublicKey: "",
    url: "",
    iv: "",
    code: "",
    appid: "",
    secret: "",
  });
};
const fnReduceThirdList = (index) => {
  thirdList.value.splice(index, 1);
};
const visibleMap = ref(false);
const handleMap = () => {
  visibleMap.value = true;
};
const fnSubmitMap = () => {
  form.value.address = `${form.value.longitude}-${form.value.latitude}`;
};
const checkThirdListItem = () => {
  for (let i = 0; i < thirdList.value.length; i++) {
    const obj = thirdList.value[i];
    if (
      !obj.thirdPlatformId ||
      !obj.thirdPlatformCode ||
      !obj.majorHazardCode
    ) {
      ElMessage.error("上级对接平台、企业编码、重大危险源编码不能为空");
      return false;
    }
  }
  return true;
};
const sectorIdRef = ref("");

const fnSubmit = debounce(
  1000,
  async () => {
    await validate();
    const check = await checkThirdListItem();
    if (check) {
      const sectorName = sectorIdRef.value.getCheckedNodes();
      const [province = "", city = "", county = ""] = form.value.area;
      const sectorId = form.value.sectorId.join(",");
      const params = {
        ...form.value,
        sectorId,
        province,
        city,
        county,
        sectorName,
        thirdList: thirdList.value,
      };
      !props.corpInfoId
        ? setBusCompanyInfoAdd(params)
        : setBusCompanyInfoUpdate(params);
      ElMessage.success("操作成功");
      emits("getData");
      visible.value = false;
    }
  },
  { atBegin: true }
);
</script>

<style scoped lang="scss">
.add-btn {
  display: flex;
  justify-content: end;
}
:deep {
  .el-input-group__append button.el-button {
    background-color: #409eff;
    color: white;
  }
}
</style>
