<template>
  <view id="unitInfoCollection" v-if="!successBool">
    <view>
      <u-notice-bar text="注：信息提交后不可修改，提交前请核对填写是否有误" :duration="7000" color="#FF0000" bgColor="#FFFFFF"></u-notice-bar>
    </view>

    <view class="centerOne" v-if="pagingBool">
      <view class="title"> 单位基本信息（1/2） </view>

      <u--form :model="form" ref="uForm" :rules="rules" labelWidth="130">
        <view style="padding: 10px 0">
          <view style="padding: 10px 10px 20px 10px; background: #ffffff">
            <view style="padding-left: 9px">
              <u-form-item label="单位名称" prop="companyName" required :borderBottom="true">
                <u-input v-model="form.companyName" placeholder="请输入单位名称" border="none">
                  <template #suffix>
                    <u-icon name="search" color="#999999" size="22" @click="companySubmit(form.companyName)"></u-icon>
                  </template>
                </u-input>
              </u-form-item>
              <u-form-item label="统一社会信用代码" prop="organization" required :borderBottom="true">
                <u-input v-model="form.organization" placeholder="请输入统一社会信用代码" border="none" maxlength="18" />
              </u-form-item>
              <u-form-item label="法人代表" prop="delegateName" required :borderBottom="true">
                <u-input v-model="form.delegateName" placeholder="请输入法人代表" border="none" />
              </u-form-item>
              <u-form-item label="所属街镇" prop="streetTown" required :borderBottom="true" @click="handleAction('所属街镇')">
                <u-input v-model="form.streetTown" placeholder="请选择所属街镇" suffixIcon="arrow-right" suffixIconStyle="color: #909399" border="none" disabledColor="transparent" disabled />
              </u-form-item>
              <u-form-item label="单位地址" prop="address" required :borderBottom="true">
                <u-input v-model="form.address" placeholder="请输入单位地址" border="none" />
              </u-form-item>
              <u-form-item label="消防管理人电话" prop="fireManagePhone" required :borderBottom="true">
                <u-input v-model="form.fireManagePhone" placeholder="请输入消防管理人电话" border="none" maxlength="11" />
              </u-form-item>
              <u-form-item label="成立时间" prop="foundTime" required :borderBottom="true" @click="handleDateTime('成立时间', 0, form.foundTime)">
                <u-input v-model="form.foundTime" placeholder="请选择成立时间" border="none" suffixIcon="calendar" suffixIconStyle="color: #909399;font-size:22px" />
              </u-form-item>
              <u-form-item label="单位使用性质" prop="companyNature" :borderBottom="true" @click="handleAction('单位使用性质')" required>
                <u-input v-model="form.companyNature" placeholder="请选择单位使用性质" suffixIcon="arrow-right" suffixIconStyle="color: #909399" border="none" disabledColor="transparent" disabled />
              </u-form-item>
              <u-form-item label="产证" prop="birthCert" :borderBottom="true" @click="handleAction('产证')" required>
                <u-input v-model="form.birthCert" placeholder="请选择产证" suffixIcon="arrow-right" suffixIconStyle="color: #909399" border="none" disabledColor="transparent" disabled />
              </u-form-item>
              <u-form-item label="单位建筑面积" prop="buildArea" :borderBottom="true" required>
                <u-input type="number" v-model="form.buildArea" placeholder="请输入单位建筑面积" suffixIcon="平方米" suffixIconStyle="color:#999999;font-size:15px" border="none" />
              </u-form-item>
              <u-form-item label="消防安全责任人" prop="fireDutyName" :borderBottom="true">
                <u-input v-model="form.fireDutyName" placeholder="请输入消防安全责任人" border="none" />
              </u-form-item>
              <u-form-item label="消防安全管理人" prop="fireManageName" :borderBottom="true">
                <u-input v-model="form.fireManageName" placeholder="请输入消防安全管理人" border="none" />
              </u-form-item>
              <u-form-item label="职工人数" prop="employeeNum" :borderBottom="true">
                <u-input type="digit" v-model="form.employeeNum" placeholder="请输入职工人数" suffixIcon="人" suffixIconStyle="color:#999999;font-size:15px" border="none" />
              </u-form-item>
              <u-form-item label="固定资产(万元）" prop="fixedAssets" :borderBottom="true">
                <u-input type="number" v-model="form.fixedAssets" placeholder="请输入固定资产(万元）" suffixIcon="万元" suffixIconStyle="color:#999999;font-size:15px" border="none" />
              </u-form-item>
            </view>
          </view>
        </view>
      </u--form>

      <view style="padding-bottom: 70px"> </view>

      <view style="position: fixed; left: 0; right: 0; bottom: 0; padding: 15px">
        <view>
          <u-button type="primary" style="width: 100%; height: 40px; font-size: 14px" @click="handleSubmit('下一步')" shape="circle"> 下一步 </u-button>
        </view>
      </view>
    </view>

    <view class="centerTwo" v-else>
      <view class="title"> 所在建筑信息（2/2） </view>

      <u--form ref="uForm1" :model="form" :rules="rules" labelWidth="130">
        <view style="padding: 10px 0" v-for="(li, index) in form.baseBuildList" :key="index">
          <view class="" style="padding: 10px 10px 20px 10px; background: #ffffff">
            <view style="display: flex; overflow: hidden">
              <image style="width: 15px; height: 15px; margin: auto 10px auto 0" src="@/static/images/unitInfoCollection/icon1.png" />
              <view style="margin: auto auto auto 0">建筑{{ index + 1 }}</view>
              <u-icon v-if="form.baseBuildList.length > 1" name="trash" color="#FF0000" size="20" style="float: right" @click="deleteSubmit('建筑', index)"></u-icon>
            </view>
            <view style="padding-left: 9px">
              <u-form-item label="建筑名称" :prop="`baseBuildList.${index}.baseBuild.buildName`" required :borderBottom="true">
                <u-input v-model="li.baseBuild.buildName" placeholder="请输入建筑名称" border="none" maxlength="30" />
              </u-form-item>
              <u-form-item label="建筑地址" :prop="`baseBuildList.${index}.baseBuild.address`" required :borderBottom="true">
                <u-input v-model="li.baseBuild.address" placeholder="请输入建筑地址" border="none" maxlength="100" />
              </u-form-item>
              <u-form-item label="建筑结构" :prop="`baseBuildList.${index}.baseBuild.buildStructure`" required :borderBottom="true" @click="handleAction('建筑结构', index)">
                <u-input
                  v-model="li.baseBuild.buildStructure"
                  placeholder="请选择建筑结构"
                  border="none"
                  suffixIcon="arrow-right"
                  suffixIconStyle="color: #909399"
                  disabledColor="transparent"
                  disabled
                />
              </u-form-item>

              <u-form-item v-if="li.baseBuild.buildStructure === '钢结构'" label="是否有防火涂层" :prop="`baseBuildList.${index}.baseBuild.fireproofCoat`" required :borderBottom="true">
                <u-radio-group v-model="li.baseBuild.fireproofCoat" placement="row">
                  <u-radio style="margin-right: 30px" :name="0" label="无"></u-radio>
                  <u-radio :name="1" label="有"></u-radio>
                </u-radio-group>
              </u-form-item>

              <u-form-item label="建筑高度" :prop="`baseBuildList.${index}.baseBuild.buildHigh`" required :borderBottom="true">
                <u-input type="number" v-model="li.baseBuild.buildHigh" placeholder="请输入建筑高度" suffixIcon="米" suffixIconStyle="color: #909399;font-size:15px" border="none" maxlength="20" />
              </u-form-item>
              <u-form-item label="地上层数" :prop="`baseBuildList.${index}.baseBuild.aboveFloor`" required :borderBottom="true">
                <u-input type="number" v-model="li.baseBuild.aboveFloor" placeholder="请输入地上层数" border="none" maxlength="5" />
              </u-form-item>
              <u-form-item label="地下层数" prop="li.underFloor" :borderBottom="true">
                <u-input type="number" v-model="li.baseBuild.underFloor" placeholder="请输入地下层数" border="none" maxlength="5" />
              </u-form-item>
              <u-form-item label="建筑面积" :prop="`baseBuildList.${index}.baseBuild.buildArea`" required :borderBottom="true">
                <u-input type="digit" v-model="li.baseBuild.buildArea" placeholder="请输入建筑面积" suffixIcon="平方米" suffixIconStyle="color:#999999;font-size:15px" border="none" maxlength="20" />
              </u-form-item>
              <u-form-item label="地下空间" prop="li.underSpace" :borderBottom="true">
                <u-input
                  type="number"
                  v-model="li.baseBuild.underSpace"
                  placeholder="请输入地下空间面积"
                  suffixIcon="平方米"
                  suffixIconStyle="color:#999999;font-size:15px"
                  border="none"
                  maxlength="20"
                />
              </u-form-item>
              <u-form-item label="建成年份" :prop="`baseBuildList.${index}.baseBuild.completeYear`" required :borderBottom="true" @click="handleDateTime('建成年份', index, li.completeYear)">
                <u-input
                  v-model="li.baseBuild.completeYear"
                  placeholder="请选择建成年份"
                  suffixIcon="calendar"
                  suffixIconStyle="color: #909399;font-size:22px"
                  border="none"
                  disabledColor="transparent"
                  disabled
                />
              </u-form-item>
              <u-form-item label="使用性质" :prop="`baseBuildList.${index}.baseBuild.useCharacter`" required :borderBottom="true" @click="handleAction('使用性质', index)">
                <u-input
                  v-model="li.baseBuild.useCharacter"
                  placeholder="请选择使用性质"
                  suffixIcon="arrow-right"
                  suffixIconStyle="color: #909399"
                  border="none"
                  disabledColor="transparent"
                  disabled
                />
              </u-form-item>

              <view
                v-if="
                  li.baseBuild.useCharacter == '生产类厂房' || li.baseBuild.useCharacter == '仓库、物流' || li.baseBuild.useCharacter == '涉及易燃易爆危险品的单位（生产、充装、储存、供应、销售等）'
                "
              >
                <view style="margin: 10px 0; text-align: center">危险品生产数量（吨/月）</view>
                <u-form-item label="甲类" prop="li.baseBuildAttach.hazardousProduceA" :borderBottom="true">
                  <u-input type="number" v-model="li.baseBuildAttach.hazardousProduceA" placeholder="请输入甲类" border="none" maxlength="24" />
                </u-form-item>
                <u-form-item label="乙类" prop="li.baseBuildAttach.hazardousProduceB" :borderBottom="true">
                  <u-input type="number" v-model="li.baseBuildAttach.hazardousProduceB" placeholder="请输入乙类" border="none" maxlength="24" />
                </u-form-item>
                <u-form-item label="丙类" prop="li.baseBuildAttach.hazardousProduceC" :borderBottom="true">
                  <u-input type="number" v-model="li.baseBuildAttach.hazardousProduceC" placeholder="请输入丙类" border="none" maxlength="24" />
                </u-form-item>
                <u-form-item label="丁戊类" prop="li.baseBuildAttach.hazardousProduceD" :borderBottom="true">
                  <u-input type="number" v-model="li.baseBuildAttach.hazardousProduceD" placeholder="请输入丁戊类" border="none" maxlength="24" />
                </u-form-item>
                <view style="margin: 10px 0; text-align: center">危险品存储数量（吨）</view>
                <u-form-item label="甲类" prop="li.baseBuildAttach.hazardousStorageA" :borderBottom="true">
                  <u-input type="number" v-model="li.baseBuildAttach.hazardousStorageA" placeholder="请输入甲类" border="none" maxlength="24" />
                </u-form-item>
                <u-form-item label="乙类" prop="li.baseBuildAttach.hazardousStorageB" :borderBottom="true">
                  <u-input type="number" v-model="li.baseBuildAttach.hazardousStorageB" placeholder="请输入乙类" border="none" maxlength="24" />
                </u-form-item>
                <u-form-item label="丙类" prop="li.baseBuildAttach.hazardousStorageC" :borderBottom="true">
                  <u-input type="number" v-model="li.baseBuildAttach.hazardousStorageC" placeholder="请输入丙类" border="none" maxlength="24" />
                </u-form-item>
                <u-form-item label="丁戊类" prop="li.baseBuildAttach.hazardousStorageD" :borderBottom="true">
                  <u-input type="number" v-model="li.baseBuildAttach.hazardousStorageD" placeholder="请输入丁戊类" border="none" maxlength="24" />
                </u-form-item>
              </view>

              <u-form-item label="消防设施设置" :prop="`baseBuildList.${index}.baseBuild.fireFacilitySystem`" required :borderBottom="true">
                <u-checkbox-group v-model="li.baseBuild.fireFacilitySystem" placement="column" @change="checkboxChange">
                  <u-checkbox :customStyle="{ marginBottom: '8px' }" label="自动喷水灭火系统" :name="1"> </u-checkbox>
                  <u-checkbox :customStyle="{ marginBottom: '8px' }" label="火灾自动报警系统" :name="2"> </u-checkbox>
                  <u-checkbox :customStyle="{ marginBottom: '8px' }" label="防排烟与排烟系统" :name="3"> </u-checkbox>
                  <u-checkbox :customStyle="{ marginBottom: '8px' }" label="消防物联网系统" :name="4"> </u-checkbox>
                </u-checkbox-group>
              </u-form-item>

              <u-form-item label="其他设施" :prop="`li.baseBuildList.baseBuild.otherSystem`" :borderBottom="true">
                <u-checkbox-group v-model="li.baseBuild.otherSystem" placement="column" @change="checkboxChange">
                  <u-checkbox :customStyle="{ marginBottom: '8px' }" label="泡沫灭火系统" :name="1"> </u-checkbox>
                  <u-checkbox :customStyle="{ marginBottom: '8px' }" label="水喷雾、细水雾灭火系统" :name="2"> </u-checkbox>
                  <u-checkbox :customStyle="{ marginBottom: '8px' }" label="消防炮、自动跟踪定位射流灭火系统" :name="3"> </u-checkbox>
                  <u-checkbox :customStyle="{ marginBottom: '8px' }" label="气体灭火系统" :name="4"> </u-checkbox>
                  <u-checkbox :customStyle="{ marginBottom: '8px' }" label="干粉灭火系统" :name="5"> </u-checkbox>
                  <u-checkbox :customStyle="{ marginBottom: '8px' }" label="其他" :name="6"> </u-checkbox>
                  <u-input v-if="li.baseBuild.otherSystem.includes(6)" v-model="li.baseBuild.otherFacilities" placeholder="请输入消防设施名称" border="none" />
                </u-checkbox-group>
              </u-form-item>

              <view>
                <view v-for="(base, baseIndex) in li.baseBuildExtinguishList" :key="baseIndex">
                  <view style="margin: 10px 0; text-align: left">
                    {{ "灭火器" + (baseIndex + 1) }}
                    <u-icon v-if="li.baseBuildExtinguishList.length > 1" name="trash" color="#FF0000" size="20" style="float: right" @click="deleteSubmit('灭火器', index, baseIndex)"></u-icon>
                  </view>

                  <u-form-item
                    label="类型"
                    :prop="`baseBuildList.${index}.baseBuildExtinguishList.${baseIndex}.extinguishType`"
                    required
                    :borderBottom="true"
                    @click="handleAction('灭火器', index, baseIndex)"
                  >
                    <u-input v-model="base.extinguishType" placeholder="请选择类型" border="none" suffixIcon="arrow-right" suffixIconStyle="color: #909399" disabledColor="transparent" disabled />
                  </u-form-item>
                  <u-form-item label="数量" :prop="`baseBuildList.${index}.baseBuildExtinguishList.${baseIndex}.extinguishNum`" :borderBottom="true" required>
                    <u-input type="number" v-model="base.extinguishNum" placeholder="请输入数量" border="none" maxlength="10" />
                  </u-form-item>
                </view>
                <u-button
                  type="primary"
                  style="width: 100px; height: 25px; margin-top: 10px"
                  v-if="li.baseBuildExtinguishList.length < 6"
                  @click="addSubmit('灭火器', index)"
                  shape="circle"
                  icon="plus"
                  :plain="true"
                  size="mini"
                >
                  添加灭火器
                </u-button>
              </view>
            </view>
          </view>
        </view>
      </u--form>

      <view style="padding-bottom: 70px">
        <u-button type="primary" style="width: 25%; height: 25px; margin-top: 10px" @click="addSubmit('建筑')" shape="circle" icon="plus" size="mini"> 添加建筑 </u-button>
      </view>

      <view style="position: fixed; left: 0; right: 0; bottom: 0; padding: 15px; background-color: transparent">
        <view style="display: flex">
          <u-button style="width: 50%; height: 40px; font-size: 14px; margin-right: 15px" @click="handleSubmit('上一步')" shape="circle" customStyle="border-color:#3c9cff;color:#3c9cff">
            上一步
          </u-button>

          <u-button type="primary" style="width: 50%; height: 40px; font-size: 14px" @click="handleSubmit('提交')" shape="circle"> 提交 </u-button>
        </view>
      </view>
    </view>

    <u-picker
      :show="actionShow"
      :columns="actionsList"
      :title="'请选择' + actionTitle"
      keyName="name"
      visibleItemCount="6"
      :defaultIndex="[actionDefaultIndex]"
      :closeOnClickOverlay="true"
      @close="actionShow = false"
      @cancel="actionShow = false"
      @confirm="selectAction"
    ></u-picker>

    <u-datetime-picker
      :show="showTime"
      v-model="timeValue"
      mode="date"
      @close="showTime = false"
      @cancel="showTime = false"
      @confirm="timeSubmit"
      :closeOnClickOverlay="true"
      :minDate="Number(new Date('1900'))"
      :maxDate="Number(new Date())"
    ></u-datetime-picker>

    <u-modal
      :show="modalShow"
      title="系统提示"
      confirmText="修改"
      cancelText="新增"
      :showCancelButton="true"
      cancelColor="#2979ff"
      @confirm="handleSubmitApi('是')"
      @cancel="handleSubmitApi('否')"
      :closeOnClickOverlay="true"
      @close="modalShow = false"
    >
      <view class="slot-content">
        <view style="text-align: center; margin-bottom: 10px">是否修改单位名称为“{{ newCompanyName }}”的信息？</view>
        <view style="text-align: center; font-size: 13px; color: #ff0000">注：“修改”则点击修改，“新增”将提交一条新的记录，如需“取消”操作可点击空白区域</view>
      </view>
    </u-modal>
  </view>

  <view v-else>
    <view style="display: flex">
      <image style="width: 120px; height: 120px; margin: 50px auto 20px auto" src="@/static/images/unitInfoCollection/success.png" />
    </view>
    <view style="text-align: center; font-weight: 600">提交成功</view>
  </view>
</template>

<script setup>
import { onLoad, onShow, onHide, onLaunch, onReady } from "@dcloudio/uni-app";
import { ref, onMounted, inject, shallowRef, reactive, toRefs, getCurrentInstance } from "vue";
import { publicStores, useStores } from "@/store/modules/index";
import { getToken } from "@/utils/auth";

import { companyByNameSelect, addBaseCompany, delBaseBuild, delBaseBuildExtinguish } from "@/api/business/mhxf/unitInfoCollection";

const { proxy } = getCurrentInstance();

const publicStore = publicStores();

const checkboxValue = ref([]);

//基本信息-单位使用性质下拉数据存储
const companyNatureList = ref([
  [
    { value: 33, name: "办公" },
    { value: 1, name: "餐饮场所" },
    { value: 2, name: "超市" },
    { value: 3, name: "宾（旅）馆" },
    { value: 4, name: "商场" },
    { value: 5, name: "集贸市场" },
    { value: 6, name: "体育场馆、会堂" },
    { value: 7, name: "影剧院、放映厅（录像厅）、礼堂等演出、放映场所" },
    { value: 8, name: "歌舞娱乐场所（含KTV、夜总会、具有娱乐功能的餐饮场所）" },
    { value: 9, name: "网吧" },
    { value: 10, name: "棋牌室" },
    { value: 11, name: "美容院(含SPA、瘦身等)" },
    { value: 12, name: "足浴" },
    { value: 13, name: "浴室(含洗浴、桑拿按摩、汗蒸等)" },
    { value: 14, name: "营业性健身、休闲场所" },
    { value: 15, name: "托儿所幼儿园" },
    { value: 16, name: "中小学校" },
    { value: 17, name: "大学" },
    { value: 18, name: "教育培训机构(含早教中心、亲子活动场所等）" },
    { value: 19, name: "养老院" },
    { value: 20, name: "福利院" },
    { value: 21, name: "医院" },
    { value: 22, name: "月子会所" },
    { value: 23, name: "公共图书馆、展览馆、博物馆" },
    { value: 24, name: "宗教活动场所" },
    { value: 25, name: "机场航站楼、客运车站候车室、客运码头候船厅" },
    { value: 26, name: "政府机关" },
    { value: 27, name: "广播电台、电视台和邮政、通信枢纽" },
    { value: 28, name: "文物保护单位" },
    { value: 29, name: "具有生产性质的厂房" },
    { value: 30, name: "大型仓库、物流企业" },
    { value: 31, name: "综合性工业企业、园区（含生产、仓库等）" },
    { value: 32, name: "其他" },
  ],
]);
//建筑-建筑结构下拉数据存储
const buildStructureList = ref([
  [
    { value: 2, name: "钢筋混凝土" },
    { value: 1, name: "砖混结构" },
    { value: 3, name: "钢结构" },
    { value: 4, name: "大型钢筋混凝土" },
    { value: 5, name: "木质结构" },
    { value: 6, name: "砖木结构" },
  ],
]);
//建筑-使用性质下拉数据存储
const useCharacterList = ref([
  [
    { value: 1, name: "大型综合体" },
    { value: 2, name: "商业" },
    { value: 3, name: "办公" },
    { value: 4, name: "住宿" },
    { value: 5, name: "科研" },
    { value: 6, name: "政府机关" },
    { value: 7, name: "医院、医疗机构" },
    { value: 8, name: "学校" },
    { value: 9, name: "宗教场所" },
    { value: 10, name: "客运站（航站楼、候船厅）" },
    { value: 11, name: "展览、博物馆" },
    { value: 12, name: "体育场馆" },
    { value: 13, name: "客运站（航站楼、候船厅）" },
    { value: 14, name: "生产类厂房" },
    { value: 15, name: "仓库、物流" },
    { value: 16, name: "涉及易燃易爆危险品的单位（生产、充装、储存、供应、销售等）" },
    { value: 17, name: "其他（需具体填写）" },
  ],
]);
//建筑-灭火器下拉数据存储
const extinguishTypeList = ref([
  [
    { value: 1, name: "水基型灭火器" },
    { value: 2, name: "干粉灭火器" },
    { value: 3, name: "洁净气体灭火器" },
    { value: 4, name: "二氧化碳灭火器" },
    { value: 5, name: "泡沫灭火器" },
    { value: 6, name: "其他灭火器" },
  ],
]);

const dataList = reactive({
  form: {
    companyName: "", //单位名称
    organization: "", //信用代码
    delegateName: "", //法人代表姓名
    streetTown: "", //所属街镇
    streetTownValue: 0, //所属街镇
    address: "", //详细地址
    fireManagePhone: "", //消防安全管理人电话
    foundTime: "", //单位成立时间

    companyNature: "", //单位使用性质
    companyNatureValue: 0, //单位使用性质
    birthCert: "", //产证
    birthCertValue: 0, //产证

    fireDutyName: "", //消防安全责任人姓名
    fireManageName: "", //消防安全管理人姓名
    employeeNum: "", //职工人数
    fixedAssets: "", //固定资产（单位：万元）
    buildArea: "", //建筑面积

    baseBuildList: [],
  },

  baseBuildListForm: {
    baseBuild: {
      buildName: "", //建筑名称
      address: "", //详细地址
      buildStructure: "", //建筑结构
      buildStructureValue: 0, //建筑结构
      aboveFloor: "", //地上楼层
      underFloor: "", //地下楼层
      buildArea: "", //建筑面积
      underSpace: "", //地下空间
      useCharacter: "", //使用性质
      useCharacterValue: 0,
      completeYear: "", //竣工年份
      buildHigh: "", //建筑高度
      fireproofCoat: 0, //是否有防火涂层
      fireFacilitySystem: [], //消防设施设置
      otherSystem: [], //其他设施
      otherFacilities: "", //其他设施名称
    },
    baseBuildAttach: {
      hazardousProduceA: null, //甲类危险品生产数量
      hazardousProduceB: null, //乙类危险品生产数量
      hazardousProduceC: null, //丙类危险品生产数量
      hazardousProduceD: null, //丁戊类危险品生产数量
      hazardousStorageA: null, //甲类危险品存储数量
      hazardousStorageB: null, //乙类危险品存储数量
      hazardousStorageC: null, //丙类危险品存储数量
      hazardousStorageD: null, //丁戊类危险品存储数量
    },
    baseBuildExtinguishList: [
      {
        extinguishType: "", //灭火器类型
        extinguishTypeValue: 0, //灭火器类型
        extinguishNum: "", //灭火器数量
        deleteFlag: null,
      },
    ],
  },

  baseBuildExtinguishArray: {
    extinguishType: "", //灭火器类型
    extinguishTypeValue: 0, //灭火器类型
    extinguishNum: "", //灭火器数量
    deleteFlag: null,
  },

  rules: {
    companyName: [
      {
        required: true,
        message: "请输入营业执照单位名称",
        trigger: ["blur", "change"],
      },
    ],
    organization: [
      {
        required: true,
        message: "请输入统一社会信用代码",
        trigger: ["blur", "change"],
      },
      {
        type: "string",
        min: 18,
        required: true,
        message: "请输入18位统一社会信用代码",
        trigger: ["change"],
      },
    ],
    delegateName: [
      {
        required: true,
        message: "请输入法人代表",
        trigger: ["blur", "change"],
      },
    ],
    streetTown: [
      {
        required: true,
        message: "请选择所属街镇",
        trigger: ["blur", "change"],
      },
    ],
    address: [
      {
        required: true,
        message: "请输入单位地址",
        trigger: ["blur", "change"],
      },
    ],
    fireManagePhone: [
      {
        required: true,
        message: "请输入消防管理人电话",
        trigger: ["blur", "change"],
      },
      {
        type: "string",
        min: 11,
        required: true,
        message: "请输入正确11位消防管理人电话",
        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        trigger: ["blur", "change"],
      },
    ],
    foundTime: [
      {
        required: true,
        message: "请选择成立时间",
        trigger: ["blur", "change"],
      },
    ],
    companyNature: [
      {
        required: true,
        message: "请选择单位使用性质",
        trigger: ["blur", "change"],
      },
    ],
    birthCert: [
      {
        required: true,
        message: "请选择产证",
        trigger: ["blur", "change"],
      },
    ],
    buildArea: [
      {
        required: true,
        message: "请输入单位建筑面积",
        trigger: ["blur", "change"],
      },
    ],

    baseBuildList: [],
  },

  baseBuildListRules: {
    baseBuild: {
      buildName: [
        {
          required: true,
          message: "请输入建筑名称",
          trigger: ["blur", "change"],
        },
      ],
      address: [
        {
          required: true,
          message: "请输入建筑地址",
          trigger: ["blur", "change"],
        },
      ],
      buildStructure: [
        {
          required: true,
          message: "请选择建筑结构",
          trigger: ["blur", "change"],
        },
      ],
      buildHigh: [
        {
          type: "number",
          required: true,
          message: "请输入建筑高度",
          trigger: ["blur", "change"],
        },
      ],
      aboveFloor: [
        {
          type: "number",
          required: true,
          message: "请输入地上层数",
          trigger: ["blur", "change"],
        },
      ],
      buildArea: [
        {
          type: "number",
          required: true,
          message: "请输入建筑面积",
          trigger: ["blur", "change"],
        },
      ],
      completeYear: [
        {
          required: true,
          message: "请选择建成年份",
          trigger: ["blur", "change"],
        },
      ],
      useCharacter: [
        {
          required: true,
          message: "请输入使用性质",
          trigger: ["blur", "change"],
        },
      ],

      fireFacilitySystem: [
        {
          type: "array",
          required: true,
          message: "请选择消防设施设置",
          trigger: ["change"],
        },
      ],
    },
    baseBuildExtinguishList: [],
  },

  baseBuildExtinguishRules: {
    extinguishType: [
      {
        required: true,
        message: "请选择灭火器类型",
        trigger: ["blur", "change"],
      },
    ],
    extinguishNum: [
      {
        type: "number",
        required: true,
        message: "请输入灭火器数量",
        trigger: ["blur", "change"],
      },
    ],
  },

  pagingBool: true,

  actionIndex: 0,
  actionIndex1: 0,
  actionTitle: "",
  actionShow: false,
  actionDefaultIndex: 0,
  actionsList: [[]],
  showTime: false, //时间选择显示隐藏
  timeValue: Number(new Date()), //时间选择值
  timeTitle: "", //时间选择标题
  timeIndex: 0, //时间选择下标

  modalShow: false,
});

const {
  form,
  baseBuildListForm,
  baseBuildExtinguishArray,
  rules,
  baseBuildListRules,
  baseBuildExtinguishRules,
  pagingBool,
  actionTitle,
  actionIndex,
  actionIndex1,
  actionsList,
  actionShow,
  actionDefaultIndex,
  showTime,
  timeValue,
  timeTitle,
  timeIndex,
  modalShow,
} = toRefs(dataList);

const uForm = ref(null);
const uForm1 = ref(null);
const newCompanyName = ref("");
const successBool = ref(false);
const scanBool = ref(false);

/**
 * @单位名称
 * @icon图标按钮点击事件
 */
function companySubmit(e) {
  actionsList.value = [[]];

  companyByNameSelect({
    companyName: e,
  }).then((res) => {
    if (res.status == "SUCCESS") {
      if (res.data.length > 0) {
        actionShow.value = true;
        res.data.forEach((el) => {
          el.name = el.companyName;
          actionsList.value[0].push(el);
        });
        actionTitle.value = "单位名称";
      } else {
        proxy.$modal.msg("未匹配到您所输入的单位！");
      }
    }
  });
}

/**
 * @上一步
 * @下一步
 * @提交
 * @按钮点击事件
 */
function handleSubmit(value) {
  if (value === "上一步") {
    pagingBool.value = true;
  } else if (value === "下一步") {
    uForm.value
      .validate()
      .then((res) => {
        uni.$u.toast("校验通过");
        pagingBool.value = false;
      })
      .catch((errors) => {
        uni.$u.toast("校验失败");
      });
  } else if (value === "提交") {
    if (newCompanyName.value == "") {
      handleSubmitApi("否");
    } else {
      modalShow.value = true;
    }
  }
}

/**
 * @api提交
 */
function handleSubmitApi(value) {
  let param = {};

  uForm1.value
    .validate()
    .then((res) => {
      uni.$u.toast("校验通过");

      param = {
        baseCompany: {
          companyName: form.value.companyName, //单位名称
          organization: form.value.organization, //组织机构代码
          address: form.value.address, //单位地址
          foundTime: form.value.foundTime + "T00:00:00", //成立时间
          companyNature: form.value.companyNatureValue, //单位使用性质
          streetTown: form.value.streetTown, //街镇
        },
        baseCompanyAttach1: {
          employeeNum: form.value.employeeNum, //职工人数
          buildArea: form.value.buildArea, //建筑面积
          fixedAssets: form.value.fixedAssets, //固定资产
          birthCert: form.value.birthCertValue, //产证
        },
        baseCompanyPerson: {
          delegateName: form.value.delegateName, //法人代表姓名
          fireDutyName: form.value.fireDutyName, //消防安全责任人姓名
          fireManageName: form.value.fireManageName, //消防安全管理人姓名
          fireManagePhone: form.value.fireManagePhone, //消防安全管理人电话
        },
        baseBuildList: [],
      };

      if (value === "是") {
        param.baseCompany.id = "id" in form.value ? form.value.id : undefined; //主键ID
        param.baseCompany.companyId = "companyId" in form.value ? form.value.companyId : undefined; //单位ID

        param.baseCompanyAttach1.id = "id1" in form.value ? form.value.id1 : undefined; //附表ID(id1)

        param.baseCompanyPerson.id = "id2" in form.value ? form.value.id2 : undefined; //单位关联人员表ID（id2）
      }

      form.value.baseBuildList.forEach((el, ind) => {
        param.baseBuildList.push({
          baseBuild: {
            buildName: el.baseBuild.buildName, //建筑名称
            address: el.baseBuild.address, //详细地址
            buildStructure: el.baseBuild.buildStructureValue, //建筑结构
            aboveFloor: Number(el.baseBuild.aboveFloor), //地上楼层
            underFloor: Number(el.baseBuild.underFloor), //地下楼层
            buildArea: Number(el.baseBuild.buildArea), //建筑面积
            underSpace: Number(el.baseBuild.underSpace), //地下空间
            useCharacter: el.baseBuild.useCharacterValue, //使用性质
            completeYear: el.baseBuild.completeYear, //竣工年份
            buildHigh: Number(el.baseBuild.buildHigh), //建筑高度
            fireFacilitySystem: el.baseBuild.fireFacilitySystem.join(","), //消防设施
            fireproofCoat: el.baseBuild.fireproofCoat, //是否有防火涂层;0、无 1、有
            otherSystem: el.baseBuild.otherSystem.join(","), //其他系统;0、无 1、有
            otherFacilities: el.baseBuild.otherFacilities, //其他设施
          },
          baseBuildAttach: {
            hazardousProduceA: Number(el.baseBuildAttach.hazardousProduceA), //甲类危险品生产数量
            hazardousProduceB: Number(el.baseBuildAttach.hazardousProduceB), //乙类危险品生产数量
            hazardousProduceC: Number(el.baseBuildAttach.hazardousProduceC), //丙类危险品生产数量
            hazardousProduceD: Number(el.baseBuildAttach.hazardousProduceD), //丁戊类危险品生产数量
            hazardousStorageA: Number(el.baseBuildAttach.hazardousStorageA), //甲类危险品存储数量
            hazardousStorageB: Number(el.baseBuildAttach.hazardousStorageB), //乙类危险品存储数量
            hazardousStorageC: Number(el.baseBuildAttach.hazardousStorageC), //丙类危险品存储数量
            hazardousStorageD: Number(el.baseBuildAttach.hazardousStorageD), //丁戊类危险品存储数量
          },
          baseBuildExtinguishList: [],
        });

        el.baseBuildExtinguishList.forEach((e, index) => {
          param.baseBuildList[ind].baseBuildExtinguishList.push({
            extinguishType: e.extinguishTypeValue,
            extinguishNum: Number(e.extinguishNum), //灭火器数量
            deleteFlag: e.deleteFlag,
          });

          if (value === "是") {
            if ("id" in e) {
              param.baseBuildList[ind].baseBuildExtinguishList[index].id = e.id;
            }
          }
        });

        if (value === "是") {
          if ("id" in el.baseBuild) {
            param.baseBuildList[ind].baseBuild.id = el.baseBuild.id;
          }
          if ("id" in el.baseBuildAttach) {
            param.baseBuildList[ind].baseBuildAttach.id = el.baseBuildAttach.id;
          }
        }
      });

      addBaseCompany(param).then((res) => {
        if (res.status == "SUCCESS") {
          if (scanBool.value) {
            successBool.value = true;
          } else {
            uni.showToast({
              title: "提交成功",
            });
            setTimeout(() => {
              proxy.$tab.reLaunch("/pages/index");
            }, 2000);
          }
        }
      });
    })
    .catch((errors) => {
      uni.$u.toast("校验失败");
    });
}

/**
 * @复选框选中事件
 */
function checkboxChange(n) {
  console.log("change", n);
}

/**
 * @action弹出框点击事件
 */
function handleAction(value, index, ind) {
  if (value == "所属街镇") {
    actionTitle.value = "所属街镇";

    actionsList.value = [
      [
        {
          name: "江川路街道",
          value: 1201,
          x: 121.399126538181,
          y: 31.0099719391863,
        },
        {
          name: "新虹街道",
          value: 1217,
          x: 121.319329296294,
          y: 31.1983901916889,
        },
        {
          name: "古美路街道",
          value: 1206,
          x: 121.388451866936,
          y: 31.1478233480159,
        },
        {
          name: "浦锦街道",
          value: 1218,
          x: 121.483929120352,
          y: 31.089967318558,
        },
        {
          name: "浦江镇",
          value: 1215,
          x: 121.524058543447,
          y: 31.0540039472667,
        },
        {
          name: "吴泾镇",
          value: 1213,
          x: 121.454076463728,
          y: 31.04860402113,
        },
        {
          name: "马桥镇",
          value: 1214,
          x: 121.352680027718,
          y: 31.0213512298508,
        },
        {
          name: "颛桥镇",
          value: 1209,
          x: 121.40607138504,
          y: 31.0612972443508,
        },
        {
          name: "莘庄镇",
          value: 1207,
          x: 121.37064864047,
          y: 31.1154549548722,
        },
        {
          name: "梅陇镇",
          value: 1212,
          x: 121.421346814491,
          y: 31.1069718313722,
        },
        {
          name: "七宝镇",
          value: 1208,
          x: 121.350366186317,
          y: 31.1553292680362,
        },
        {
          name: "虹桥镇",
          value: 1211,
          x: 121.37956256207,
          y: 31.1806219953212,
        },
        {
          name: "华漕镇",
          value: 1210,
          x: 121.277541517147,
          y: 31.2289121171624,
        },
        {
          name: "莘庄工业区",
          value: 1216,
          x: 121.376508452784,
          y: 31.0678185611843,
        },
      ],
    ];

    if (form.value.streetTown) {
      actionsList.value[0].forEach((el, ind) => {
        if (el.name === form.value.streetTown) {
          actionDefaultIndex.value = ind;
        }
      });
    } else {
      actionDefaultIndex.value = 0;
    }
  }

  if (value == "单位使用性质") {
    actionTitle.value = "单位使用性质";

    actionsList.value = companyNatureList.value;

    actionDefaultIndex.value = 0;
  }

  if (value == "产证") {
    actionTitle.value = "产证";

    actionsList.value = [
      [
        {
          value: 1,
          name: "商业服务业设施用地(商业设施、商务设施、娱乐康体设施、公用设施营业网点、其它服务设施等)",
        },
        {
          value: 2,
          name: "工业用地",
        },
        {
          value: 3,
          name: "居住用地",
        },
        {
          value: 4,
          name: "公共管理与公共服务用地(行政办公、文化设施、教育科研、体育、医疗卫生、社会福利设施、文物古迹、外事、宗教设施等",
        },
        {
          value: 5,
          name: "物流仓储用地",
        },
        {
          value: 6,
          name: "道路与交通设施用地",
        },
        {
          value: 7,
          name: "公用设施用地",
        },
        {
          value: 8,
          name: "绿地与广场用地",
        },
      ],
    ];

    actionDefaultIndex.value = 0;
  }

  if (value == "建筑结构") {
    actionTitle.value = "建筑结构";
    actionIndex.value = index;

    actionsList.value = buildStructureList.value;
    actionDefaultIndex.value = 0;
  }

  if (value == "使用性质") {
    actionTitle.value = "使用性质";
    actionIndex.value = index;

    actionsList.value = useCharacterList.value;
    actionDefaultIndex.value = 0;
  }

  if (value == "灭火器") {
    actionTitle.value = "灭火器";
    actionIndex.value = index;
    actionIndex1.value = ind;

    actionsList.value = extinguishTypeList.value;
    actionDefaultIndex.value = 0;
  }

  actionShow.value = true;
}

/**
 * @action弹出框选择事件
 */
function selectAction(e) {
  if (actionTitle.value == "单位名称") {
    form.value.baseBuildList = [];
    rules.value.baseBuildList = [];

    newCompanyName.value = e.value[0].companyName;
    // form.value = e.value[0];
    form.value.id = e.value[0].id;
    form.value.id1 = e.value[0].id1;
    form.value.id2 = e.value[0].id2;
    form.value.companyId = e.value[0].companyId;

    form.value.companyName = e.value[0].companyName;
    form.value.organization = e.value[0].organization;
    form.value.delegateName = e.value[0].delegateName;
    form.value.address = e.value[0].address;
    form.value.foundTime = e.value[0].foundTime.split("T")[0];

    if (e.value[0].baseBuildList != null) {
      form.value.baseBuildList = e.value[0].baseBuildList;
    } else {
      form.value.baseBuildList.push(baseBuildListForm.value);
    }

    form.value.baseBuildList.forEach((el, index) => {
      rules.value.baseBuildList.push(JSON.parse(JSON.stringify(baseBuildListRules.value)));

      el.baseBuild.fireFacilitySystem = el.baseBuild.fireFacilitySystem ? el.baseBuild.fireFacilitySystem.split(",").map((num) => Number(num)) : [];
      el.baseBuild.otherSystem = el.baseBuild.otherSystem ? el.baseBuild.otherSystem.split(",").map((num) => Number(num)) : [];

      //建筑结构
      buildStructureList.value[0].forEach((e) => {
        if (e.value == el.baseBuild.buildStructure) {
          el.baseBuild.buildStructureValue = el.baseBuild.buildStructure;
          el.baseBuild.buildStructure = e.name;
        }
      });

      //使用性质
      useCharacterList.value[0].forEach((e) => {
        if (e.value == el.baseBuild.useCharacter) {
          el.baseBuild.useCharacterValue = el.baseBuild.useCharacter;
          el.baseBuild.useCharacter = e.name;
        }
      });

      el.baseBuildAttach
        ? el.baseBuildAttach
        : (el.baseBuildAttach = {
            hazardousProduceA: "", //甲类危险品生产数量
            hazardousProduceB: "", //乙类危险品生产数量
            hazardousProduceC: "", //丙类危险品生产数量
            hazardousProduceD: "", //丁戊类危险品生产数量
            hazardousStorageA: "", //甲类危险品存储数量
            hazardousStorageB: "", //乙类危险品存储数量
            hazardousStorageC: "", //丙类危险品存储数量
            hazardousStorageD: "", //丁戊类危险品存储数量
          });

      el.baseBuildExtinguishList ? el.baseBuildExtinguishList : (el.baseBuildExtinguishList = []);

      extinguishTypeList.value[0].forEach((e) => {
        el.baseBuildExtinguishList.forEach((f) => {
          if (e.value == f.extinguishType) {
            f.extinguishTypeValue = f.extinguishType;
            f.extinguishType = e.name;
          }
        });
      });

      el.baseBuildExtinguishList.forEach((f) => {
        rules.value.baseBuildList[index].baseBuildExtinguishList.push(JSON.parse(JSON.stringify(baseBuildExtinguishRules.value)));
      });
    });
  }

  if (actionTitle.value == "所属街镇") {
    form.value.streetTown = e.value[0].name;
    form.value.streetTownValue = e.value[0].value;
  }

  if (actionTitle.value == "单位使用性质") {
    form.value.companyNature = e.value[0].name;
    form.value.companyNatureValue = e.value[0].value;
  }

  if (actionTitle.value == "产证") {
    form.value.birthCert = e.value[0].name;
    form.value.birthCertValue = e.value[0].value;
  }

  if (actionTitle.value == "建筑结构") {
    form.value.baseBuildList[actionIndex.value].baseBuild.buildStructure = e.value[0].name;
    form.value.baseBuildList[actionIndex.value].baseBuild.buildStructureValue = e.value[0].value;
  }

  if (actionTitle.value == "使用性质") {
    form.value.baseBuildList[actionIndex.value].baseBuild.useCharacter = e.value[0].name;
    form.value.baseBuildList[actionIndex.value].baseBuild.useCharacterValue = e.value[0].value;
  }

  if (actionTitle.value == "灭火器") {
    form.value.baseBuildList[actionIndex.value].baseBuildExtinguishList[actionIndex1.value].extinguishType = e.value[0].name;
    form.value.baseBuildList[actionIndex.value].baseBuildExtinguishList[actionIndex1.value].extinguishTypeValue = e.value[0].value;
  }

  actionShow.value = false;
}

/**
 * @时间弹出框点击事件
 */
function handleDateTime(value, index, time) {
  showTime.value = true;
  if (value == "成立时间") {
    timeValue.value = time ? Number(new Date(time)) : Number(new Date());
    timeIndex.value = index;
    timeTitle.value = "成立时间";
  } else if (value == "建成年份") {
    timeValue.value = time ? Number(new Date(time)) : Number(new Date());
    timeIndex.value = index;
    timeTitle.value = "建成年份";
  }
}

/**
 * @时间选择器
 * @确定按钮事件
 */
function timeSubmit(data) {
  let time = publicStore.formatterDateTime(data.value);
  let timeData = time.split(" ")[0];
  if (timeTitle.value == "成立时间") {
    form.value.foundTime = timeData;
  } else if (timeTitle.value == "建成年份") {
    form.value.baseBuildList[timeIndex.value].baseBuild.completeYear = timeData;
  }
  showTime.value = false;
}

/**
 * @添加建筑
 * @添加灭火器
 * @按钮点击事件
 */
function addSubmit(type, index) {
  if (type === "建筑") {
    form.value.baseBuildList.push(JSON.parse(JSON.stringify(baseBuildListForm.value)));
    rules.value.baseBuildList.push(JSON.parse(JSON.stringify(baseBuildListRules.value)));
  } else if (type == "灭火器") {
    form.value.baseBuildList[index].baseBuildExtinguishList.push(JSON.parse(JSON.stringify(baseBuildExtinguishArray.value)));
    rules.value.baseBuildList[index].baseBuildExtinguishList.push(JSON.parse(JSON.stringify(baseBuildExtinguishRules.value)));
  }
}

/**
 * @删除建筑
 * @删除灭火器
 * @按钮点击事件
 */
function deleteSubmit(type, index, baseIndex) {
  if (type == "建筑") {
    if ("id" in form.value.baseBuildList[index].baseBuild) {
      delBaseBuild(form.value.baseBuildList[index].baseBuild.id).then((res) => {
        if (res.status == "SUCCESS") {
          form.value.baseBuildList.splice(index, 1);
        }
      });
    } else {
      form.value.baseBuildList.splice(index, 1);
    }
    rules.value.baseBuildList.splice(index, 1);
  } else if (type == "灭火器") {
    if ("id" in form.value.baseBuildList[index].baseBuildExtinguishList[baseIndex]) {
      delBaseBuildExtinguish(form.value.baseBuildList[index].baseBuildExtinguishList[baseIndex].id).then((res) => {
        if (res.status == "SUCCESS") {
          form.value.baseBuildList[index].baseBuildExtinguishList.splice(baseIndex, 1);
        }
      });
    } else {
      form.value.baseBuildList[index].baseBuildExtinguishList.splice(baseIndex, 1);
    }

    rules.value.baseBuildList[index].baseBuildExtinguishList.splice(baseIndex, 1);
  }
}

onLoad((options) => {
  form.value.baseBuildList = [];
  rules.value.baseBuildList = [];

  addSubmit("建筑");

  if (options.scanBool) {
    scanBool.value = options.scanBool;
    if (scanBool.value) {
      document.getElementsByClassName("uni-page-head-hd")[0].style.cssText = "display: none;";
    }
  }
});

onShow(() => {
  //调用系统主题颜色
  proxy.$settingStore.systemThemeColor([1]);
});
</script>

<style lang="scss">
#unitInfoCollection {
  .centerOne,
  .centerTwo {
    .title {
      color: #333333;
      text-align: center;
      margin-top: 10px;
    }
  }

  :deep(.u-picker__view__column__item) {
    font-size: 13px;
  }
}
</style>
