<template>
  <MOSTY.FromPage :title="props.formData.title" @closeDialog="closeDialog">
    <template #content>
      <MOSTY.Assort :title="'基础信息'" />
      <el-form :model="props.formData" ref="ruleFormRef" label-position="right" :rules="rules" label-width="181px"
               :disabled='!props.formData.saveBtnShow'>

        <el-form-item label="场所名称:" prop="placename">
          <el-input v-model="props.formData.placename" style="width: 335px" />
        </el-form-item>
        <el-form-item label="场所等级:">
          <div style="width: 335px;">
            <MOSTY.DictRidioAndSelect :dictData="D_ORG_ORGLEVEL" v-model="props.formData.departmentlevel"
                                      selectType="select" :disabled="false" />
          </div>
        </el-form-item>
        <el-form-item label="场所类型:" prop="sitetype">
          <div style="width: 335px;">
            <MOSTY.DictRidioAndSelect :dictData="D_TB_CSLX" v-model="props.formData.sitetype" selectType="select"
                                      :disabled="false" />
          </div>
        </el-form-item>
        <el-form-item label="是否设置装卸防高坠措施:" prop="fgzFlag" v-if='props.formData.sitetype == "04"'>
          <div style="width: 335px;">
            <MOSTY.DictRidioAndSelect :dictData="D_BZ_SF" v-model="props.formData.fgzFlag" selectType="radio"
                                      :disabled="false" />
          </div>
        </el-form-item>
        <el-form-item label="修建时间:">
          <el-date-picker v-model="props.formData.builddate" style="width: 335px" type="date" format="YYYY-MM-DD"
                          value-format="YYYY-MM-DD" placeholder="请选择修建时间" :disabled-date="disablednowDate1" />
        </el-form-item>
        <el-form-item label="占地面积:" prop="area">
          <el-input v-model.number="props.formData.area" @blur="props.formData.area = JEblurFn(props.formData.area)"
                    type="number" style="width: 335px;">
            <template #append>平方米</template>
          </el-input>
        </el-form-item>
        <el-form-item label="场所状态:" prop="ynxzf">
          <div style="width: 335px;">
            <MOSTY.DictRidioAndSelect :dictData="D_TB_CSZT" v-model="props.formData.ynxzf" selectType="select"
                                      :disabled="false" />
          </div>
        </el-form-item>
        <el-form-item v-if="props.formData.ynxzf == '2'" label="出租面积:" prop='hireArea'>
          <el-input v-model.number="props.formData.hireArea"
                    @blur="props.formData.hireArea = JEblurFn(props.formData.hireArea)" type="number"
                    style="width: 335px">
            <template #append>平方米</template>
          </el-input>
        </el-form-item>
        <el-form-item v-if="props.formData.ynxzf == '4'" label="闲置面积:" prop='hireArea'>
          <el-input v-model.number="props.formData.hireArea" type="number"
                    @blur="props.formData.hireArea = JEblurFn(props.formData.hireArea)" style="width: 335px">
            <template #append>平方米</template>
          </el-input>
        </el-form-item>
        <el-form-item label="出租用途:" v-if="props.formData.ynxzf == '2'" prop='hireUse'>
          <div style="width: 335px;">
            <MOSTY.DictRidioAndSelect :dictData="D_BZ_JZWCZYT" v-model="props.formData.hireUse" selectType="select"
                                      :disabled="false" />
          </div>
        </el-form-item>

        <el-form-item label="地图经纬度:" prop="longitude" style="display: flex;">
          <el-input v-model="props.formData.longitude" clearable style="width:129px" placeholder="经度" />
          <el-input v-model="props.formData.latitude" clearable style="width: 129px" placeholder="维度" />
          <el-button @click="Chooesmap" style='padding:10px 9px;'>地图描点</el-button>
        </el-form-item>
        <el-form-item v-if="props.formData.id" label="使用状态:" prop="useState"
                      :rules="[{ required: true, message: '请选择使用状态', trigger: 'blur' }]">
          <div style="width: 335px;">
            <MOSTY.DictRidioAndSelect :dictData="D_BZ_SYZT" v-model="props.formData.useState" selectType="radio"
                                      :disabled="false" />
          </div>
        </el-form-item>
        <el-form-item label="地址:" prop='address'>
          <MOSTY.DictTree :zdbh="'D_BZ_XZQH'" v-model="props.formData.xzqhcode" :placeholder='"请选择行政区划"'
                          :type="'xzqh'"
                          :disabled='props.formData.disabled' style="width: 335px;" @nameChange='getxzqh' />
          <el-input v-model="props.formData.address" placeholder="请输入详细地址" style="width: 517px;" />
        </el-form-item>
        <el-form-item label="场所信息图片:" style='width:100%;'>
          <div style='display:flex;'>
            <MOSTY.ErwmImg v-if="props.formData.id"
                           :url="qrcodeImg(props.formData.id, 'S', props.formData.deptname, props.formData.placename)"
                           :filename='"场所二维码"' />
            <MOSTY.Upload :width="'100%'" :limit="5" :nopicer="false" :isImg="true" :ShowfileList="false"
                          v-model="props.formData.venuefile" :nameshow='true' :gsgfList="['jpg', 'png']"
                          :disabled='!props.formData.saveBtnShow' @filehandleChange="changeFiles">
            </MOSTY.Upload>
          </div>
        </el-form-item>
      </el-form>
      <MOSTY.Assort :title="'管理信息'" />
      <el-form :model="props.formData" ref="ruleFormRef2" label-position="right" :rules="rules2" label-width="181px"
               :disabled='!props.formData.saveBtnShow'>
        <el-form-item label="所属单位:" prop="orgname">
          <el-input v-model="props.formData.orgname" disabled style="width: 335px" />
        </el-form-item>
        <el-form-item label="责任部门:" prop="deptname">
          <el-input v-model="props.formData.deptname" placeholder="请选择责任部门" clearable readonly
                    style="width: 335px">
            <template #append>
              <el-button class='cursor' @click="ChooesDdld('01')">选择</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="场所负责人:" prop="postusername" style="display: flex;width:100%;">
          <el-input v-model="props.formData.postusername" type="textarea" :rows="4" readonly style="width: 93%"
                    clearable>
          </el-input>
          <el-button class='cursor ml10' @click="ChooesDdld('02')">选择</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='props.formData.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' :type='"cs"' :obj='props.formData' @handleChange="changelicolor"
                           @resetChange='resetChange' />
          </div>
        </div>
        <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='"cs"' :obj='props.formData' @handleChange="changelicolor2" />
          </div>
        </div>
      </div>
    </template>
    <template #footer>
      <el-button type="primary" @click="saveData(ruleFormRef)" v-loading="saveloading"
                 v-if='props.formData.saveBtnShow'>
        <el-icon>
          <DocumentChecked />
        </el-icon>
        保存
      </el-button>
      <el-button @click="closeDialog">
        <el-icon>
          <DocumentDelete />
        </el-icon>
        关闭
      </el-button>
    </template>
    <template #dwbox>
      <div class="mapbox" v-if="mapshow">
        <BigMap @close="mapshow = false" @point="changpoint" />
      </div>
      <!-- 选择部门 -->
      <Choosebm :showDdld="showDept" :searchType="'01'" :deptId="getItem('deptId').ssdwid" @closezzjg="closezzjg"
                @listdata="getSonValue" :zzlx="zzlx" />

      <!-- 选择场所负责人 -->
      <ChooseUser v-model="chooseUserVisible" :Single="singleShow" :data="memberList" :deptId="props.formData.deptid"
                  @choosedUsers="getSonValue">
      </ChooseUser>
    </template>
  </MOSTY.FromPage>

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

const { proxy } = getCurrentInstance()
const {
  D_ORG_ORGLEVEL,
  D_TB_CSLX,
  D_TB_CSZT,
  D_BZ_JZWCZYT,
  D_BZ_JZWWQBWCLXN,
  D_BZ_JZJGLX,
  D_BZ_JZWHZWXXLB,
  D_BZ_SYZT,
  D_BZ_SF
} = proxy.$dict("D_ORG_ORGLEVEL", "D_TB_CSLX", "D_TB_CSZT", "D_BZ_JZWCZYT", "D_BZ_JZWWQBWCLXN",
  "D_BZ_JZJGLX", "D_BZ_JZWHZWXXLB", "D_BZ_SYZT", "D_BZ_SF")
const rules = {
  placename: [{
    required: true,
    message: "请输入场所名称",
    trigger: "blur"
  }],
  sitetype: [{
    required: true,
    message: "请选择场所类型",
    trigger: "blur"
  }],
  fgzFlag: [{
    required: true,
    message: "请选择是否设置防高坠措施",
    trigger: "blur"
  }],
  xzqhcode: [{
    required: true,
    message: "请选择地址行政区划",
    trigger: "blur"
  }],
  address: [{
    required: true,
    message: "请输入地址",
    trigger: "blur"
  }],
  ...rule.znumberRule({
    validator: true,
    require: true
  }, "area"),
  ...rule.znumberRule({
    validator: true,
    require: true
  }, "hireArea"),
  hireUse: [{
    required: true,
    message: "请输入出租用途",
    trigger: "blur"
  }],
  ynxzf: [{
    required: true,
    message: "请选择场所状态",
    trigger: "blur"
  }],
  longitude: [{
    required: true,
    message: "请选择经纬度",
    trigger: "blur"
  }],
  thermalMaterials: [{
    required: true,
    message: "建筑物外墙保温材料性能不能为空",
    trigger: "blur"
  }],
  buildingStructure: [{
    required: true,
    message: "建筑结构不能为空",
    trigger: "blur"
  }],
  fireLevel: [{
    required: true,
    message: "火灾危险性分类不能为空",
    trigger: "blur"
  }]

}
const rules2 = {
  deptname: [{
    required: true,
    message: "请选择责任部门",
    trigger: "blur"
  }],
  postusername: [{
    required: true,
    message: "请选择场所负责人",
    trigger: "blur"
  }],
  orgname: [{
    required: true,
    message: "请选择所属单位",
    trigger: "blur"
  }]
}
const ruleFormRef = ref()
const ruleFormRef2 = ref()
const mapshow = ref(false)
const saveloading = ref(false)
const zzlx = ref(null)
const showDept = ref(false)
const isShowgd = ref(true)
const isShowdt = ref(true)
const chooseUserVisible = ref(false) //选择领导弹窗
const singleShow = ref(true) //单选多选
const memberList = ref([])
const tablist = ref([
  // {
  //   title: "建筑物",
  //   num: 0,
  //   icon: "jianzhuwu",
  //   actives: true,
  //   components: defineAsyncComponent(() => import("@/components/MyComponents/TabList/SynthesizeNew.vue"))
  // },
  // {
  //   title: "安全设备设施",
  //   num: 0,
  //   icon: "sbss2",
  //   actives: false,
  //   components: defineAsyncComponent(() => import("@/components/MyComponents/TabList/Security.vue"))
  // },
  // {
  //   title: "安全器材",
  //   num: 0,
  //   icon: "sbss2",
  //   actives: false,
  //   components: defineAsyncComponent(() => import("@/components/MyComponents/TabList/Apparatus.vue"))
  // },
  // {
  //   title: "安全标识",
  //   num: 0,
  //   icon: "sbss2",
  //   actives: false,
  //   components: defineAsyncComponent(() => import("@/components/MyComponents/TabList/Safetysigns.vue"))
  // },
  // {
  //   title: "生产设备设施",
  //   num: 0,
  //   icon: "sbss2",
  //   actives: false,
  //   components: defineAsyncComponent(() => import("@/components/MyComponents/TabList/Produce.vue"))
  // },
  // {
  //   title: "变配电设备设施",
  //   num: 0,
  //   icon: "sbss2",
  //   actives: false,
  //   components: defineAsyncComponent(() => import("@/components/MyComponents/TabList/Distributing.vue"))
  // },
  // {
  //   title: "特种设备",
  //   num: 0,
  //   icon: "sbss2",
  //   actives: false,
  //   components: defineAsyncComponent(() => import("@/components/MyComponents/TabList/Equipment.vue"))
  // }
])
const tablist2 = ref([
  // {
  //   title: "检查标准",
  //   num: 0,
  //   icon: "jianzhuwu",
  //   sblx: "100000000000",
  //   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"))
  // }
])
const emits = defineEmits(["saveSuccess"])
// 接收子组件传来的
const props = defineProps({
  formData: {
    type: Object,
    default: {}
  },
  type: {
    type: String,
    default: "1"
  }
})

onMounted(() => {
  props.formData.area = props.formData.area ? Number(props.formData.area).toFixed(2) : null
  props.formData.hireArea = props.formData.hireArea ? Number(props.formData.hireArea).toFixed(2) : null

  if (props.formData.id) {
    props.formData.useState = "01"
    getjzwcount()
    getaqbscount()
    getscsbsscount()
    getbpdcount()
    getaqsbsscount()
    getaqqccount()
    gettzsbcount()
    getCount()

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

// 关闭弹窗
function closeDialog() {
  if (props.formData.saveBtnShow) {
    proxy.$modal.confirm("离开会丢失页面中修改的内容，确认离开吗？")
      .then(() => {
        ruleFormRef.value.resetFields()
        ruleFormRef.value.clearValidate()
        emits("saveSuccess")
      })
      .catch(() => {
        // catch error
      })
  } else {
    ruleFormRef.value.resetFields()
    ruleFormRef.value.clearValidate()
    emits("saveSuccess")
  }

}

//建筑物总数
function getjzwcount() {
  getApi({ siteid: props.formData.id }, "/mosty-jcgl/building/countAllBuild").then(res => {
    tablist.value[0].num = res ? res : 0
  })
}

//安全设备设施总数
function getaqsbsscount() {
  postApi({
    siteid: props.formData.id,
    type: "1"
  }, "/mosty-jcgl/sbglAqsbss/countAll").then(res => {
    tablist.value.forEach(item => {
      if (item.title == "安全设备设施") {
        item.num = res ? res : 0
      }
    })
  })

}

//安全器材总数
function getaqqccount() {
  postApi({
    siteid: props.formData.id,
    type: "1"
  }, "/mosty-jcgl/sbglAqqc/countAll").then(res => {
    tablist.value.forEach(item => {
      if (item.title == "安全器材") {
        item.num = res ? res : 0
      }
    })
  })
}

//安全标识总数
function getaqbscount() {
  postApi({
    siteid: props.formData.id,
    type: "1"
  }, "/mosty-jcgl/sitelogo/countAllSitelogo").then(res => {
    tablist.value[3].num = res ? res : 0
  })
}

//生产设备设施总数
function getscsbsscount() {
  postApi({
    siteid: props.formData.id,
    type: "1"
  }, "/mosty-jcgl/sbglScsbss/countAll").then(res => {
    tablist.value[4].num = res ? res : 0
  })
}

//特种设备总数
function gettzsbcount() {
  postApi({
    siteid: props.formData.id,
    type: "1"
  }, "/mosty-jcgl/sbglTzsb/countAll").then(res => {
    tablist.value.forEach(item => {
      if (item.title == "特种设备") {
        item.num = res ? res : 0
      }
    })
  })
}

//变配电设备设施总数
function getbpdcount() {
  postApi({
    siteid: props.formData.id,
    type: "1"
  }, "/mosty-jcgl/sbglBpdsb/countAll").then(res => {
    tablist.value[5].num = res ? res : 0
  })
}

//获取风险清单总数
function getCount() {
  getApi({ siteid: props.formData.id }, "/mosty-jcgl/dynamic/riskStatistics").then(res => {
    tablist2.value.forEach(item => {
      if (item.title == "风险清单") {
        item.num = res ? res.R + res.O + res.Y + res.B : 0
      }
    })
  })
}

function changpoint(val) {
  props.formData.longitude = val.lng.toFixed(7)
  props.formData.latitude = val.lat.toFixed(7)
}

function changelicolor(val) {
  tablist.value.forEach(item => {
    if (item.title == val.title) {
      item.actives = true
    } else {
      item.actives = false
    }
  })
  if (val.title == "安全设备设施") {
    getaqsbsscount()
  } else if (val.title == "安全器材") {
    getaqqccount()
  } else if (val.title == "安全标识") {
    getaqbscount()
  } else if (val.title == "生产设备设施") {
    getscsbsscount()
  } else if (val.title == "变配电设备设施") {
    getbpdcount()
  } else if (val.title == "建筑物") {
    getjzwcount()
  } else if (val.title == "特种设备") {
    gettzsbcount()
  }

}

function changelicolor2(val) {
  tablist2.value.forEach(item => {
    if (item.title == val.title) {
      item.actives = true
    } else {
      item.actives = false
    }
  })
  if (val.title == "风险清单") {
    getCount()
  }

}

//刷新接口
function resetChange(val) {
  if (val == "jzw") {
    getjzwcount()
  } else if (val == "aqbs") {
    getaqbscount()
  } else if (val == "aqqc") {
    getaqqccount()
  } else if (val == "scsb") {
    getscsbsscount()
  } else if (val == "bpdsb") {
    getbpdcount()
  } else if (val == "aqsbss") {
    getaqsbsscount()
  } else if (val == "tzsb") {
    gettzsbcount()
  }
}

//选择部门
function ChooesDdld(val) {
  zzlx.value = val
  if (val == "01") {
    showDept.value = true
  } else {
    if (props.formData.deptid) {
      memberList.value = props.formData.postuserid ? props.formData.postuserid.split(",") : []
      singleShow.value = false
      chooseUserVisible.value = true
    } else {
      ElMessage.error("请先选择责任部门！!")
    }

  }
}

const getSonValue = (value) => {
  if (zzlx.value == "01") {
    props.formData.deptname = value.orgName
    props.formData.deptid = value.id

  } else {
    props.formData.postusername = value.map(item => {
      if (item.mobile) {
        return item.userName + "（" + item.mobile + "）"
      } else {
        return item.userName
      }
    }).toString()
    props.formData.postuserid = value.map(item => {
      return item.id
    }).toString()
  }
}

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

//选择地图描点
function Chooesmap() {
  mapshow.value = true
}

//获取行政区划名称
function getxzqh(val) {
  props.formData.xzqh = val
}

// 保存数据
const saveData = async (formEl) => {
  saveloading.value = true
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      ruleFormRef2.value.validate((valid) => {
        if (valid) {
          props.formData.venuefile = props.formData.venuefile
            ? props.formData.venuefile.toString()
            : null
          props.formData.sketchingfile = props.formData.sketchingfile
            ? props.formData.sketchingfile.toString()
            : null
          props.formData.xzqhcode = props.formData.xzqhcode ? props.formData.xzqhcode.toString() : ""
          props.formData.area = props.formData.area ? parseFloat(props.formData.area) : null
          props.formData.hireArea = props.formData.hireArea ? parseFloat(props.formData.hireArea) : null
          if (!props.formData.id) {
            postApi(props.formData, "/mosty-jcgl/site/addSceneSiteOne")
              .then((res) => {
                ElMessage.success("新增成功")
                emits("saveSuccess")
              }).finally(() => {
              saveloading.value = false
            })

          } else {
            postApi(props.formData, "/mosty-jcgl/site/updateSceneSiteOne")
              .then((res) => {
                ElMessage.success("修改成功")
                emits("saveSuccess")
              }).finally(() => {
              saveloading.value = false
            })

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

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

</script>

<style lang="scss" scoped>
.mapbox {
  width: 100% !important;
  height: 100% !important;
  position: absolute;
  top: 0;
  left: 0;
}

::v-deep .el-form-item__content {
  margin-left: 0px !important;
}

// ::v-deep .el-form-item__content {
//   margin-left: 10px !important;
// }

::v-deep .el-form {
  // width: 1580px;
  margin: auto;
  padding: 10px;
  margin-top: 10px;
  flex-wrap: wrap;
  justify-content: start;
}

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

::v-deep ::-webkit-scrollbar {
  display: none !important;
}
</style>
