<template>
  <div class="bigBox">
    <MOSTY.FromPage :title="props.formData.title" @closeDialog="black">
      <template #content>
        <MOSTY.Assort :title="'基础信息'" />
        <el-form class="mosty-from-wrap" ref="ruleFormRef" label-width="150px" :model="fromData" :inline="true"
                 :rules="rules" :disabled="!props.formData.saveBtnShow">
          <!-- 公共都有的start -->
          <el-form-item label="设备设施类型:" prop="sblx">
            <MOSTY.DictTree v-model="fromData.sblx" :zdlist="sblxlist" :placeholder='"请选择设备设施类型"'
                            :type='"array"' style="width: 337px;" @onChange='cahngesblx' />
          </el-form-item>
          <el-form-item label="设备设施名称:" prop="name"
                        :rules="[{ required: true, message: '请输入设备设施名称', trigger: 'blur' }]">
            <el-input v-model="fromData.name" placeholder="请输入设备设施名称" style="width: 337px"></el-input>
          </el-form-item>
          <el-form-item label="品牌型号:">
            <el-input v-model="fromData.brandModel" placeholder="请输入品牌型号" style="width: 337px"></el-input>
          </el-form-item>
          <!-- 公共都有的end -->
          <!-- 工业梯台 -->
          <template v-if="filterList.gytd.includes(fromData.sblx)">
            <el-form-item label="梯台类型:" prop="landingType"
                          :rules="[{ required: true, message: '请选择梯台类型', trigger: 'blur' }]">
              <MOSTY.DictRidioAndSelect :dictData="D_BZ_TTLX" v-model="fromData.landingType"
                                        style="width: 337px" selectType="select" />
            </el-form-item>
            <el-form-item label="高度:" prop="height">
              <el-input v-model.number="fromData.height" type='number' placeholder="请输入高度"
                        style="width: 337px">
                <template #append>米</template>
              </el-input>
            </el-form-item>
            <el-form-item label="投入使用日期:" prop="usertime">
              <el-date-picker v-model="fromData.usertime" type="date" value-format="YYYY-MM-DD"
                              style="width: 337px" placeholder="请选择投入使用日期" :disabled-date="disabledazrq" />
            </el-form-item>
          </template>
          <!-- 办公后勤 -->
          <template v-else-if="filterList.bghq.includes(fromData.sblx)">
            <el-form-item label="功率:" prop="power">
              <el-input v-model.number="fromData.power" type='number' placeholder="请输入功率"
                        style="width: 337px">
                <template #append>千瓦</template>
              </el-input>
            </el-form-item>
            <el-form-item label="接地情况:" prop="jdqk">
              <MOSTY.DictRidioAndSelect :dictData="D_BZ_SF" v-model="fromData.jdqk" selectType="select"
                                        :disabled="!props.formData.saveBtnShow" style="width: 337px" />
            </el-form-item>
            <el-form-item label="投入使用日期:" prop="usertime">
              <el-date-picker v-model="fromData.usertime" type="date" value-format="YYYY-MM-DD"
                              style="width: 337px" placeholder="请选择投入使用日期" :disabled-date="disabledazrq" />
            </el-form-item>
          </template>
          <!-- 剩余的所有 -->
          <template v-else>
            <el-form-item label="生产厂家:" prop="sccj">
              <el-input v-model="fromData.sccj" placeholder="请输入生产厂家" style="width: 337px"></el-input>
            </el-form-item>
            <el-form-item label="功率:" prop="power">
              <el-input v-model.number="fromData.power" type='number' placeholder="请输入功率"
                        style="width: 337px">
                <template #append>千瓦</template>
              </el-input>
            </el-form-item>
            <el-form-item label="接地情况:" prop="jdqk">
              <MOSTY.DictRidioAndSelect :dictData="D_BZ_SF" v-model="fromData.jdqk" selectType="select"
                                        :disabled="!props.formData.saveBtnShow" style="width: 337px" />
            </el-form-item>
            <el-form-item label="投入使用日期:" prop="usertime">
              <el-date-picker v-model="fromData.usertime" type="date" value-format="YYYY-MM-DD"
                              style="width: 337px" placeholder="请选择投入使用日期" :disabled-date="disabledazrq" />
            </el-form-item>
          </template>
          <el-form-item label="所属场所:" prop="sitename" v-if="['cs', 'jzw', 'lc', 'bw'].includes(addtype)">
            <el-input v-model="fromData.sitename" style="width: 337px" disabled />
          </el-form-item>
          <!-- <el-form-item label="所属场所:" prop="sitename"
              v-if="['scsbss', 'stsbss'].includes(addtype) && fromData.id">
              <el-input v-model="fromData.sitename" style="width: 337px" disabled />
          </el-form-item> -->
          <!--  && !fromData.id -->
          <el-form-item label="所属场所:" prop="sitename" v-if="['scsbss', 'stsbss'].includes(addtype)">
            <el-select v-model="fromData.sitename" @change="cahngecsmc" clearable style="width: 337px"
                       placeholder="请选择">
              <el-option v-for="item in csmclist" :key="item" :label="item.placename" :value="item.id" />
            </el-select>
          </el-form-item>
          <!-- && !fromData.id -->
          <el-form-item :label="fromData.publicarea == '1' ? '所属场区:' : '所属建筑物:'" prop="buildingname"
                        v-if="['cs', 'scsbss', 'stsbss'].includes(addtype)">
            <el-select v-model="fromData.buildingname" @change="cahngejzwmc" clearable style="width: 337px"
                       placeholder="请选择">
              <el-option v-for="item in jzwlist" :key="item" :label="item.buildingname"
                         :value="item.id" />
            </el-select>
          </el-form-item>
          <!-- 'cs', 'jzw', 'lc', 'bw', 'scsbss', 'stsbss' -->
          <el-form-item :label="fromData.publicarea == '1' ? '所属场区:' : '所属建筑物:'" prop="buildingname"
                        v-if="['jzw', 'lc', 'bw'].includes(addtype) && fromData.id">
            <el-input v-model="fromData.buildingname" style="width: 337px" disabled />
          </el-form-item>
          <el-form-item :label="fromData.publicarea == '1' ? '所属场区:' : '所属建筑物:'" prop="buildingname"
                        v-if="['jzw', 'lc', 'bw'].includes(addtype) && !fromData.id">
            <el-input v-model="fromData.buildingname" style="width: 337px" disabled />
          </el-form-item>
          <!-- && !fromData.id -->
          <el-form-item label="所属楼层:" prop="floorname"
                        v-if="['cs', 'jzw', 'scsbss', 'stsbss'].includes(addtype) && fromData.publicarea != '1'">
            <el-select v-model="fromData.floorname" @change="cahngelcmc" clearable style="width: 337px"
                       placeholder="请选择">
              <el-option v-for="item in lclist" :key="item" :label="item.floorname" :value="item.id" />
            </el-select>
          </el-form-item>
          <!-- 'cs', 'jzw', 'lc', 'bw', 'scsbss', 'stsbss' -->
          <el-form-item label="所属楼层:" prop="floorname"
                        v-if="['lc', 'bw',].includes(addtype) && fromData.id && fromData.publicarea != '1'">
            <el-input v-model.number="fromData.floorname" style="width: 337px" disabled />
          </el-form-item>
          <el-form-item label="所属楼层:" prop="floorname"
                        v-if="['lc', 'bw'].includes(addtype) && !fromData.id && fromData.publicarea != '1'">
            <el-input v-model.number="fromData.floorname" style="width: 337px" disabled />
          </el-form-item>
          <!-- && !fromData.id -->
          <el-form-item :label="fromData.publicarea == '1' ? '场区部位:' : '所属部位:'" prop="partname"
                        v-if="['cs', 'jzw', 'lc', 'scsbss', 'stsbss'].includes(addtype)">
            <el-select v-model="fromData.partname" @change="cahngebw" clearable style="width: 337px"
                       placeholder="请选择">
              <el-option v-for="item in bwlist" :key="item"
                         :label="item.partname ? item.partname : item.qtmc" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item :label="fromData.publicarea == '1' ? '场区部位:' : '所属部位:'" prop="partname"
                        v-if="['bw'].includes(addtype) && !fromData.id">
            <el-input v-model="fromData.partname" disabled style="width: 337px" />
          </el-form-item>
          <!-- 'cs', 'jzw', 'lc', 'bw', 'scsbss', 'stsbss' -->
          <el-form-item :label="fromData.publicarea == '1' ? '场区部位:' : '所属部位:'" prop="partname"
                        v-if="['bw'].includes(addtype) && fromData.id">
            <el-input v-model="fromData.partname" disabled style="width: 337px" />
          </el-form-item>
          <el-form-item label="安装位置:" prop="location">
            <el-input v-model="fromData.location" placeholder="请输入安装位置" clearable
                      style="width: 337px"></el-input>
          </el-form-item>
          <el-form-item label="检测周期:" prop="detectionTime">
            <el-input v-model="fromData.detectionTime" type="number" style="width: 337px"
                      placeholder="请输入检测周期">
              <template #append>月</template>
            </el-input>
          </el-form-item>
          <el-form-item label="检测日期:" prop="sycjcrq">
            <el-date-picker v-model="fromData.sycjcrq" type="date" value-format="YYYY-MM-DD"
                            style="width: 337px" placeholder="请选择检测日期" />
          </el-form-item>
          <el-form-item label="检查周期:" prop="inspectTime">
            <el-input v-model="fromData.inspectTime" type="number" style="width: 337px"
                      placeholder="请输入检查周期">
              <template #append>月</template>
            </el-input>
          </el-form-item>
          <el-form-item label="报废时间:" prop="scrapTime">
            <el-date-picker v-model="fromData.scrapTime" type="date" value-format="YYYY-MM-DD"
                            style="width: 337px" placeholder="请选择报废时间" />
          </el-form-item>
          <el-form-item v-if="fromData.id" label="状态:" prop="state">
            <div style="width: 337px;">
              <MOSTY.DictRidioAndSelect :dictData="D_BZ_SYZT" v-model="fromData.state" selectType="radio"
                                        :disabled="false" />
            </div>
          </el-form-item>
          <el-form-item label="内部编号:" prop="nbbh" v-if="fromData.id">
            <el-input v-model="fromData.nbbh" disabled style="width: 337px"></el-input>
          </el-form-item>
          <el-form-item label="设备资料:" style="width: 100%;" prop="deviceFile">
            <MOSTY.Upload :width="'100%'" :limit="5" :nopicer="true"
                          placeholder="请上传设备资料（pdf,ofd,doc,docx,xls,xlsx）" :isImg="false" ShowfileList
                          :disabled="!props.formData.saveBtnShow" v-model="fromData.deviceFile" :nameshow='true'
                          :gsgfList="['pdf', 'ofd', 'doc', 'docx', 'xls', 'xlsx']">
            </MOSTY.Upload>
          </el-form-item>
          <el-form-item label="其它资料:" style="width: 100%;" prop="otherFile">
            <MOSTY.Upload :width="'100%'" :limit="5" :nopicer="true" :isImg="false" ShowfileList
                          :disabled="!props.formData.saveBtnShow"
                          placeholder="请上传其他资料（pdf,ofd,doc,docx,xls,xlsx）"
                          v-model="fromData.otherFile" :nameshow='true'
                          :gsgfList="['pdf', 'ofd', 'doc', 'docx', 'xls', 'xlsx']">
            </MOSTY.Upload>
          </el-form-item>
          <el-form-item label="图片:" style="width: 100%;">
            <div style='display:flex;'>
              <MOSTY.ErwmImg
                :url="qrcodeImg(props.formData.id, 'sbss', fromData.sitename, fromData.buildingname, `${fromData.name}(${fromData.nbbh})`)"
                :filename='"设备设施二维码"' v-if="props.formData.id" />
              <MOSTY.Upload :width="'100%'" :limit="5" :nopicer="false" :isImg="true"
                            :ShowfileList="false" v-model="fromData.picture" :nameshow='true'
                            :gsgfList="['jpg', 'png']" @filehandleChange="changeFiles"
                            :disabled="!props.formData.saveBtnShow">
              </MOSTY.Upload>
            </div>
          </el-form-item>
        </el-form>
        <MOSTY.Assort :title="'管理信息'" />
        <el-form class="mosty-from-wrap" ref="ruleFormRef2" label-width="130px" :model="fromData" :inline="true"
                 :rules="rules2" :disabled="!props.formData.saveBtnShow">
          <el-form-item label="责任部门:" prop="responsibilitydeptname">
            <el-input v-model="fromData.responsibilitydeptname" style="width: 337px">
              <template #append>
                <el-button class='cursor' @click="ChooesDdld('02')">选择</el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="设备负责人:" prop="responsibilitypersonname" style="display: flex;width:100%;">
            <el-input v-model="fromData.responsibilitypersonname" type="textarea" :rows="4" readonly
                      style="width: 93%" clearable>
            </el-input>
            <el-button class='cursor ml10' @click="ChooesDdld('01')">选择</el-button>
          </el-form-item>
          <el-form-item label="巡查相关方：" prop="xgfMc">
            <XiangGFSelect style="width: 337px" v-model="formData.xgfMc" v-model:id="formData.xgfId"
                           @change="xgfDwChange"  @update:modelValue="updateModelValue" @update:id = 'updateId' />
          </el-form-item>
          <el-form-item label="相关方责任人：" prop="xgfRyMc">
            <XiangGFRen inputWidth="337px" v-model:ids="formData.xgfRyId" v-model:cName="formData.xgfRyMc" :relatedid="formData.xgfId"
                        :disabled="!formData.xgfId" @update:ids="updateIds" @update:cName="updateName"/>
          </el-form-item>
        </el-form>
        <div v-if='fromData.id'>
          <MOSTY.Assort :title="'关联信息(固定信息、动态信息)'" />
          <div>
            <div class='table-lable'>
              <span>固定信息</span>
              <img :src="getImgUrl('img/icon-jt.png')" style='cursor:pointer'
                   @click='isShowgd = !isShowgd' />
            </div>
            <div v-show='isShowgd'>
              <MOSTY.TabList :tablist='tablist' :obj='fromData' :showCount='false' :cardtype="'03'"
                             :isEdit="props.formData.saveBtnShow" @handleChange="changelicolor" />
            </div>
            <div class='table-lable'>
              <span>动态信息</span>
              <img :src="getImgUrl('img/icon-jt.png')" style='cursor:pointer'
                   @click='isShowdt = !isShowdt' />
            </div>
            <div v-show='isShowdt'>
              <MOSTY.TabList :tablist='tablist2' :type='"sb"' :obj='fromData'
                             @handleChange="changelicolor2" @resetChange="searchChange" />
            </div>
          </div>
        </div>
      </template>
      <template #footer>

        <el-button type="primary" @click="submit(ruleFormRef)" v-loading='saveloading'
                   v-if="props.formData.saveBtnShow">
          <el-icon>
            <DocumentChecked />
          </el-icon>
          保存
        </el-button>
        <el-button @click="black">
          <el-icon>
            <DocumentDelete />
          </el-icon>
          关闭
        </el-button>
      </template>
      <template #dwbox>
        <!-- 选择部门 -->
        <Choosebm :showDdld="showDept" @closezzjg="closezzjg" @listdata="getSonValue" :zzlx="zzlx" />
        <ChooseUser v-model="chooseUserVisible" :Single="singleShow" :data="memberList"
                    @choosedUsers="getSonValue" :deptId='fromData.responsibilitydeptid'></ChooseUser>
      </template>
    </MOSTY.FromPage>
  </div>
</template>

<script setup>
import { getImgUrl } from "@/utils/tools.js"
import { ref, getCurrentInstance, defineAsyncComponent, onMounted } from "vue"
import * as MOSTY from "@/components/MyComponents/index"
import Choosebm from "@/components/MyComponents/ChooseDept/index.vue"
import ChooseUser from "@/components/MyComponents/ChooseUser/Leader.vue"
import { ElMessage } from "element-plus"
import * as rule from "@/utils/rules.js"
import { getApi, postApi } from "@/api/tobAcco_api.js"
import { qrcodeImg, disablednowDate1 } from "@/utils/tools.js"
import XiangGFSelect from "@/components/dialog/component/XiangGFSelect.vue"
import XiangGFRen from "@/components/dialog/component/XiangGFRen.vue"

const { proxy } = getCurrentInstance()
const { D_BZ_TTLX, D_BZ_SYZT, D_BZ_SF } = proxy.$dict("D_BZ_TTLX", "D_BZ_SYZT", "D_BZ_SF")
const rules = {
  buildingname: [{ required: true, message: "请选择所属建筑物", trigger: "blur" }],
  sitename: [{ required: true, message: "请选择所属场所", trigger: "blur" }],
  floorname: [{ required: true, message: "请选择所属楼层", trigger: "blur" }],
  partname: [{ required: true, message: "请选择所属部位", trigger: "blur" }],
  sblx: [{ required: true, message: "请选择设备设施类型", trigger: "blur" }],
  ...rule.numberzzsRule({ validator: true, require: true, num: 99999 }, "fjPower"),
  ccrq: [{ required: true, message: "请选择出厂日期", trigger: "change" }],
  usertime: [{ required: true, message: "请选择投入使用日期", trigger: "change" }],
  jdqk: [{ required: true, message: "请输入接地情况", trigger: "change" }],
  state: [{ required: true, message: "请选择状态", trigger: "change" }],
  location: [{ required: true, message: "请输入安装位置", trigger: "blur" }],
  ...rule.numberzzsRule({ validator: true, require: false, num: 120 }, "inspectTime"),
  ...rule.numberzzsRule({ validator: true, require: false, num: 120 }, "detectionTime"),
  sycjcrq: [{ required: false, message: "请选择检测日期", trigger: "blur" }],
  scrapTime: [{ required: false, message: "请选择报废时间", trigger: "blur" }]

}
const rules2 = {
  responsibilitypersonname: [{ required: true, message: "请选择设备负责人", trigger: "change" }],
  responsibilitydeptname: [{ required: true, message: "请选择责任部门", trigger: "change" }]
}
const props = defineProps({
  formData: {
    type: Object,
    default: {}
  },
  obj: {
    type: Object,
    default: {}
  },
  type: {
    default: "",
    type: String
  },
  // /** 哪里调用,方便特殊设置 */
  // from: String,
  /** 食堂id */
  canteenInfoId: String
})
const isShowdt = ref(true)
const showDept = ref(false)
const saveloading = ref(false)
const isShowgd = ref(true)
const addtype = ref("scsbss")
const csmclist = ref([])
const jzwlist = ref([])
const lclist = ref([])
const bwlist = ref([])
const sblxlist = ref([])
const emit = defineEmits("changePage", 'createPage')
const ruleFormRef = ref()
const ruleFormRef2 = ref()
const fromData = ref({ state: "01" })
const chooseUserVisible = ref(false) //选择领导弹窗
const singleShow = ref(true) //单选多选
const memberList = ref([])
const zzlx = ref(null)
// 打叶复烤
const filterList = ref({
  gytd: ["200401130000", "200402030000", "200403090000"],
  bghq: ["200404010000", "200404020000", "200404030000", "200404040000", "200404050000", "200404060000"]
})
const tablist = ref([
  {
    title: "风险告知卡",
    num: 0,
    icon: "sbss2",
    actives: true,
    components: defineAsyncComponent(() => import("@/components/MyComponents/TabList/Fxgzk.vue"))
  },
  {
    title: "安全装置",
    num: 0,
    icon: "sbss2",
    opt: { type: "01" },
    actives: false,
    components: defineAsyncComponent(() => import("@/components/MyComponents/TabList/Area.vue"))
  }
])
const tablist2 = ref([
  {
    title: "检查标准",
    num: 0,
    icon: "sbss2",
    sblx: "",
    actives: true,
    components: defineAsyncComponent(() => import("@/components/MyComponents/TabList/Synthesize.vue"))
  },
  {
    title: "检查记录",
    num: 0,
    icon: "sbss2",
    actives: false,
    components: defineAsyncComponent(() => import("@/components/MyComponents/TabList/Standard.vue"))
  },
  {
    title: "风险清单",
    num: 0,
    icon: "sbss2",
    actives: false,
    components: defineAsyncComponent(() => import("@/components/MyComponents/TabList/Risklist.vue"))
  },
  {
    title: "隐患清单",
    num: 0,
    icon: "sbss2",
    actives: false,
    components: defineAsyncComponent(() => import("@/components/MyComponents/TabList/Pitfall.vue"))
  },
  {
    title: "维保记录",
    num: 0,
    icon: "sbss2",
    actives: false,
    components: defineAsyncComponent(() => import("@/components/MyComponents/TabList/Maintenance.vue"))
  }
])
onMounted(() => {


  addtype.value = props.formData.type ? props.formData.type : "scsbss"
  fromData.value.siteid = props.formData.siteid ? props.formData.siteid : null
  fromData.value.sitename = props.formData.sitename ? props.formData.sitename : null
  fromData.value.buildingid = props.formData.buildingid ? props.formData.buildingid : null
  fromData.value.buildingname = props.formData.buildingname ? props.formData.buildingname : null
  fromData.value.floorid = props.formData.floorid ? props.formData.floorid : null
  fromData.value.floorname = props.formData.floorname ? props.formData.floorname : null
  fromData.value.partid = props.formData.partid ? props.formData.partid : null
  fromData.value.partname = props.formData.partname ? props.formData.partname : null
  fromData.value.publicarea = props.formData.publicarea ? props.formData.publicarea : null
  fromData.value.sfcq = props.formData.sfcq ? props.formData.sfcq : null
  fromData.value.saveBtnShow = props.formData.saveBtnShow
  fromData.value.xgfRyId = props.formData.xgfRyId ? props.formData.xgfRyId : null;
  fromData.value.xgfRyMc = props.formData.xgfRyMc ? props.formData.xgfRyMc : null;
  fromData.value.xgfMc = props.formData.xgfMc ? props.formData.xgfMc : null;
  fromData.value.xgfId = props.formData.xgfId ? props.formData.xgfId : null;

  tablist2.value[0].sblx = fromData.value.sblx
  if (props.formData.id) {
    // getaqzzcount()
    getmain(props.formData.id)
  } else {
    if (props.formData.type == "cs") {
      getjzwlist(props.formData.siteid)
    } else if (props.formData.type == "jzw") {
      if (props.formData.publicarea == "1") {
        getbw2data(props.formData.buildingid)
      } else {
        getlcdata(props.formData.buildingid)
      }
    } else if (props.formData.type == "lc") {
      getbwdata(props.formData.floorid)
    } else if (["scsbss", "stsbss"].includes(addtype.value)) {
      getcsData()
    }
  }
  if (["stsbss"].includes(addtype.value)) {
    if (tablist.value.at(-1).title == "安全装置") {
      tablist.value.pop()
    }
    if (tablist2.value.at(-1).title == "维保记录") {
      tablist2.value.pop()
    }
  }
  getsblb()

})

// 获取相关方责任人id
const updateIds = (ids) => {
  fromData.value.xgfRyId = ids;
}
// 获取相关方人员列表
const updateName = (names) => {
  fromData.value.xgfRyMc = names;
}
// 获取检查方名称
const updateModelValue = (ModelValue) => {
  fromData.value.xgfMc = ModelValue;
}
// 获取检查方id
const updateId = (id) => {
  fromData.value.xgfId = id;
}

function change() {
  fromData.value.usertime = ""
}

//安全装置总数
// function getaqzzcount() {
//     getApi({ zbid: props.formData.id }, '/mosty-jcgl/SbglAqzz/countTbSbglAqzz').then(res => {
//         tablist.value[1].num = res ? res : 0
//     })
// }
function disabledazrq(time) {
  return time.getTime() + 24 * 60 * 60 * 1000 < new Date(fromData.value.ccrq).getTime() || time.getTime() > Date.now()
}

//根据操作人 查询 场所
function getcsData() {
  getApi({}, "/mosty-jcgl/site/getSiteListByUser").then((res) => {
    csmclist.value = res
  })
}

//获取场所选择
const cahngecsmc = (val) => {
  csmclist.value.forEach((item) => {
    if (item.id == val) {
      fromData.value.siteid = item.id
      fromData.value.sitename = item.placename
      fromData.value.buildingname = ""
      fromData.value.buildingid = ""
      fromData.value.publicarea = ""
      fromData.value.floorname = ""
      fromData.value.floorid = ""
      fromData.value.partname = ""
      fromData.value.partid = ""
      getjzwlist(item.id)

    }
  })
}
//获取当前部位
const cahngebw = (val) => {
  bwlist.value.forEach((item) => {
    if (item.id == val) {
      fromData.value.partid = item.id
      fromData.value.partname = item.partname ? item.partname : item.qtmc

    }
  })
}

//	根据placeid，查询建筑物
function getjzwlist(placeid) {
  getApi({ placeid }, "/mosty-jcgl/building/queryBuildingByPlaceid").then(res => {
    jzwlist.value = res ? res : []
  })
}

//获取建筑物名称
function cahngejzwmc(val) {
  jzwlist.value.forEach((item) => {
    if (item.id == val) {
      fromData.value.buildingid = item.id
      fromData.value.buildingname = item.buildingname
      fromData.value.publicarea = item.publicarea
      fromData.value.floorname = ""
      fromData.value.floorid = ""
      fromData.value.partname = ""
      fromData.value.partid = ""
      if (item.publicarea == "1") {
        getbw2data(item.id)
      } else {
        getlcdata(item.id)
      }
    }
  })
}

//根据建筑物查询楼层
function getlcdata(id) {
  getApi({ id }, "/mosty-jcgl/floor/queryFloorByBuildId").then(res => {
    lclist.value = res ? res : []
  })
}

//获取楼层名称
function cahngelcmc(val) {
  lclist.value.forEach((item) => {
    if (item.id == val) {
      fromData.value.floorid = item.id
      fromData.value.floorname = item.floorname
      fromData.value.partname = ""
      fromData.value.partid = ""
      getbwdata(item.id)
    }
  })
}

//获取设备设施类型
function getsblb() {
  /**  @type {Array} 食堂数组
   * 200404020000	蒸饭柜	ZFK	2
   * 200404030000	抽油烟机和排烟管道	CYYJHPYGD	3
   * 200404050000	液化气瓶	YHQP	5
   * 200404070000	灶具设备	ZJSB	7
   * 200404080000	炊事机械设备	CSJXSB	8
   * 200404090000	调理设备	TLSB	9
   * 200404100000	制冷保温设备	ZLBWSB	10
   * 200404110000	消毒设备	XDSB	11
   */
  let diningHallArr = ["200404020000", "200404030000", "200404050000", "200404070000", "200404080000", "200404090000", "200404100000", "200404110000"]
  if (["stsbss"].includes(addtype.value) || props.obj.from === "食堂管理") {
    getApi({ zdbh: "D_TB_JCYWLX", dm: "200404", level: 5 }, "/mosty-base/sysDict/getJcyelxDictTree").then(res => {
      sblxlist.value = res[0].itemList
      sblxlist.value = sblxlist.value.filter(item => {
        return diningHallArr.includes(item.dm)
      })
    })
  } else {
    getApi({ zdbh: "D_TB_JCYWLX", dm: "2004", level: 5 }, "/mosty-base/sysDict/getJcyelxDictTree").then(res => {
      let arr = Array.isArray(res?.[0]?.itemList) ? res[0].itemList : []
      // 不包含食堂数据
      sblxlist.value = arr.map(item => {
        if (Array.isArray(item.itemList)) {
          item.itemList = item.itemList.filter(child => {
            return !diningHallArr.includes(child.dm)
          })
        }
        return item
      })
    })
  }

}

// (新)根据楼层id查询部位
function getbwdata(id) {
  getApi({ id }, "/mosty-jcgl/part/getListByFloorid").then((res) => {
    bwlist.value = res ? res : []
  })
}

//(新)根据建筑物id查询部位
function getbw2data(id) {
  getApi({ id }, "/mosty-jcgl/part/getListByBuildid").then((res) => {
    bwlist.value = res ? res : []
  })
}

function changelicolor(val) {
  tablist.value.forEach(item => {
    if (item.title == val.title) {
      item.actives = true
    } else {
      item.actives = false
    }
  })
}

function changelicolor2(val) {
  tablist2.value.forEach(item => {
    if (item.title == val.title) {
      item.actives = true
    } else {
      item.actives = false
    }
  })
}

//点击领导选择按钮
function ChooesDdld(val) {
  zzlx.value = val
  memberList.value = []
  if (val == "01") {
    if (fromData.value.responsibilitydeptid) {
      memberList.value = fromData.value.responsibilityperson ? fromData.value.responsibilityperson.split(",") : []
      singleShow.value = false
      chooseUserVisible.value = true
    } else {
      ElMessage.error("请先选择责任部门！!")
    }

  } else {
    showDept.value = true
  }

}

const getSonValue = (value) => {
  if (zzlx.value == "01") {
    fromData.value.responsibilitypersonname = value.map(item => {
      if (item.mobile) {
        return item.userName + "（" + item.mobile + "）"
      } else {
        return item.userName
      }
    }).toString()
    fromData.value.responsibilityperson = value.map(item => {
      return item.id
    }).toString()
  } else {
    fromData.value.responsibilitydeptname = value.orgName
    fromData.value.responsibilitydeptid = value.id

  }

}

//关闭弹窗
const closezzjg = (val) => {
  showDept.value = val
}

//获取设备类型名称
function cahngesblx(val) {
  if (val.dm != "200404060000") {
    fromData.value.name = val.label
  }

}

// 保存
const submit = async (ruleFormRef) => {
  saveloading.value = true
  if (!ruleFormRef) return
  await ruleFormRef.validate((valid) => {
    if (valid) {
      ruleFormRef2.value.validate((valid) => {
        if (valid) {
          fromData.value.picture = fromData.value.picture ? fromData.value.picture.toString() : null
          fromData.value.deviceFile = fromData.value.deviceFile?.toString()
          fromData.value.otherFile = fromData.value.otherFile?.toString()
          if (props.canteenInfoId) fromData.value.canteenInfoId = props.canteenInfoId
          if (fromData.value) {
            if (fromData.value.id) {
              postApi(fromData.value, "/mosty-jcgl/sbglScsbss/updateTbSbglScsbssOne")
                .then((res) => {
                  ElMessage.success("修改成功")
                  emit("changePage")
                }).finally(() => {
                saveloading.value = false
              })
            } else {
              postApi(fromData.value, "/mosty-jcgl/sbglScsbss/addTbSbglScsbssOne")
                .then((res) => {
                  ElMessage.success("新增成功")
                  // emit("changePage", res)
                  emit("createPage", res)
                }).finally((err) => {
                saveloading.value = false
              })
            }


          }
        } else {
          ElMessage.error("请输入必填项!")
          saveloading.value = false
        }
      })
    } else {
      ElMessage.error("请输入必填项!")
      saveloading.value = false
    }
  })
}

//获取详情
function getmain(id) {
  if (id) {
    getApi({ id: id }, "/mosty-jcgl/sbglScsbss/queryTbSbglScsbssById").then((res) => {
      if (res) {
        res.responsibilitypersonname = res.responsibilitypersonname ? res.responsibilitypersonname.replace(/（null）/g, "") : ""
        fromData.value = res
        fromData.value.saveBtnShow = props.formData.saveBtnShow
        getlcxq(fromData.value.buildingid)
        gettotal()
        if (props.formData.type == "cs") {
          getjzwlist(res.siteid)
        } else if (props.formData.type == "lc") {
          getbwdata(res.floorid)
        } else if (["scsbss", "stsbss"].includes(addtype.value)) {
          getcsData()
        }
        if (res.partid) {
          getApi({ id: res.partid }, "/mosty-jcgl/part/queryScenePartById").then(res => {
            if (res) {
              fromData.value.partname = res.partname ? res.partname : res.qtmc
            }
          })
        }

      }
    })
  }
}

const searchChange = () => {
  gettotal()
}

//获取统计
function gettotal() {
  postApi({
    bizId: fromData.value.id,
    bizType: fromData.value.sblx
  }, "/mosty-jcgl/deviceUpkeepRecord/statistics").then(res => {
    tablist2.value.forEach(item => {
      if (item.title.includes(["维保记录"])) {
        item.num = res ? res : 0
      }
    })
  })
}

//获取建筑物详情
function getlcxq(id) {
  getApi({}, `/mosty-jcgl/building/getBuildingById/${id}`).then(res => {
    fromData.value.publicarea = res.publicarea ? res.publicarea : "2"
    if (fromData.value.publicarea == "1") {
      getbw2data(id)
    } else {
      getlcdata(id)
    }
  })
}

const black = () => {
  if (props.formData.saveBtnShow) {
    proxy.$modal.confirm("离开会丢失页面中修改的内容，确认离开吗？")
      .then(() => {
        // 关闭上一次的表单校验
        ruleFormRef.value.clearValidate()
        emit("changePage")
      })
      .catch(() => {
        // catch error
      })
  } else {
    // 关闭上一次的表单校验
    ruleFormRef.value.clearValidate()
    emit("changePage")
  }

}


</script>

<style lang="scss" scoped>
::v-deep .el-form-item__content {
  margin-left: 0px !important;
}

.table-lable {
  margin: 10px;
  color: var(--el-color-primary);
}

::v-deep ::-webkit-scrollbar {
  display: none !important;
}

::v-deep .el-pagination {
  justify-content: center !important;
}

::v-deep .el-form {
  margin: auto;
  padding: 10px;
  margin: 10px 20px;
  flex-wrap: wrap;
  justify-content: start;

}


.el-form-item {
  display: flex;
  margin-right: 20px;
}

.bigBox {
  display: block !important;
  padding: 0px !important;
  box-sizing: border-box;
}


::v-deep .el-table .cell {
  padding: 0 0 !important;
}

::v-deep .el-table--border .el-table__cell .cell {
  padding-left: 0px !important;

  > input {
    width: 100%;
    height: 33px;
  }
}


::v-deep .el-upload-list {
  width: 50%;
}
</style>
