<template>
  <div class="bigBox">
    <MOSTY.FromPage :title="props.formData.title" @closeDialog="closeDialog">
      <template #content>
        <MOSTY.Assort :title="'基础信息'" />
        <el-form class="mosty-from-wrap" ref="ruleFormRef" label-width="130px" :model="fromData" :inline="true"
                 :rules="rules" :disabled="!props.formData.saveBtnShow">

          <el-form-item label="安全标识名称:" prop="logoname">
            <el-input v-model="fromData.logoname" placeholder="请输入安全标识名称" style="width: 337px"
                      clearable></el-input>
          </el-form-item>
          <el-form-item label="标识类型:" prop="aqbslb">
            <MOSTY.DictTree v-model="fromData.aqbslb" :zdlist="aqbslist" :placeholder='"请选择标识类型"'
                            :type='"array"' style="width: 337px" />
          </el-form-item>
          <el-form-item label="业务分类:" prop="logotypecode">
            <div style="width:100%;">
              <MOSTY.DictRidioAndSelect :dictData="D_TB_AQBS_LX" v-model="fromData.logotypecode"
                                        selectType="select" :disabled="false" style="width: 337px" />
            </div>
          </el-form-item>

          <el-form-item label="安装日期:" prop="installationdate">
            <el-date-picker v-model="fromData.installationdate" type="date" value-format="YYYY-MM-DD"
                            placeholder="请选择安装日期" style="width: 337px" :disabled-date="disabledDate" />
          </el-form-item>
          <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="['aqbs'].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="['aqbs'].includes(addtype)">
            <el-select v-model="fromData.sitename" @change="cahngecsmc" style="width: 337px" clearable
                       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', 'aqbs'].includes(addtype)">
            <el-select v-model="fromData.buildingname" @change="cahngejzwmc" clearable style="width: 337px"
                       :placeholder="fromData.publicarea == '1' ? '请选择所属场区:' : '请选择所属建筑物:'">
              <el-option v-for="item in jzwlist" :key="item" :label="item.buildingname"
                         :value="item.id" />
            </el-select>
          </el-form-item>

          <!-- 'cs', 'jzw', 'lc', 'bw', 'aqbs' -->
          <el-form-item :label="fromData.publicarea == '1' ? '所属场区:' : '所属建筑物:'" prop="buildingname"
                        v-if="['jzw', 'lc', 'bw'].includes(addtype) && fromData.id">
            <el-input v-model="fromData.buildingname" disabled style="width: 337px" />
          </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" disabled style="width: 337px" />
          </el-form-item>
          <!-- && !fromData.id -->
          <el-form-item label="所属楼层:" prop="floorname"
                        v-if="['cs', 'jzw', 'aqbs'].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', 'aqbs' -->
          <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', 'aqbs'].includes(addtype)">
            <el-select v-model="fromData.partname" @change="cahngebw" clearable style="width: 337px"
                       :placeholder="fromData.publicarea == '1' ? '请选择场区部位:' : '请选择所属部位:'">
              <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', 'aqbs' -->
          <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="请输入悬挂位置" style="width: 337px"
                      clearable></el-input>
          </el-form-item>
          <el-form-item v-if="fromData.id" label="状态:" prop="state">
            <div style="width: 100%;">
              <MOSTY.DictRidioAndSelect :dictData="D_BZ_SYZT" style="width: 337px"
                                        v-model="fromData.state" selectType="radio" :disabled="false" />
            </div>
          </el-form-item>

          <el-form-item label="图片:" style='width:100% !important;'>
            <MOSTY.Upload :width="'100%'" :limit="5" :nopicer="false" :isImg="true" :ShowfileList="false"
                          v-model="fromData.file" :nameshow='true' :gsgfList="['jpg', 'png']"
                          :disabled="!props.formData.saveBtnShow" @filehandleChange="changeFiles">
            </MOSTY.Upload>
          </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" style="justify-content: start !important;">
          <el-form-item label="责任部门:" prop="responsibledeptname">
            <el-input v-model="fromData.responsibledeptname" style="width: 337px" readonly clearable>
              <template #append>
                <el-button class='cursor' @click="ChooesDdld('01')">选择</el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="责任人:" prop="responsibleusername" style="display: flex;width:100%;">
            <el-input v-model="fromData.responsibleusername" 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>
      </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.responsibledeptid'></ChooseUser>
      </template>
    </MOSTY.FromPage>
  </div>
</template>

<script setup>
import {
  reactive,
  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 { getApi, deleteApi, putApi, postApi } 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_TB_AQBS_LX,
  D_BZ_SYZT
} = proxy.$dict("D_TB_AQBS_LX", "D_BZ_SYZT")
const rules = {
  sitename: [{
    required: true,
    message: "请选择场所名称",
    trigger: "blur"
  }],
  buildingname: [{
    required: true,
    message: "请选择所属建筑物",
    trigger: "blur"
  }],
  floorname: [{
    required: true,
    message: "请选择所属楼层",
    trigger: "blur"
  }],
  partname: [{
    required: true,
    message: "请选择所属部位",
    trigger: "blur"
  }],
  aqbslb: [{
    required: true,
    message: "请选择标识类型",
    trigger: "blur"
  }],
  logotypecode: [{
    required: true,
    message: "请选择业务分类",
    trigger: "blur"
  }],
  logoname: [{
    required: true,
    message: "请输入安全标识名称",
    trigger: "change"
  }],
  installationdate: [{
    required: true,
    message: "请选择安装日期",
    trigger: "change"
  }],
  location: [{
    required: true,
    message: "请输入悬挂位置",
    trigger: "change"
  }],
  // status: [{ required: true, message: "请选择使用状态", trigger: "change" }],
  state: [{
    required: true,
    message: "请选择使用状态",
    trigger: "change"
  }]

}
const saveloading = ref(false)
const rules2 = {
  responsibleusername: [{
    required: true,
    message: "请选择设备负责人",
    trigger: "change"
  }],
  responsibledeptname: [{
    required: true,
    message: "请选择责任部门",
    trigger: "change"
  }]
}
const props = defineProps({
  formData: {
    type: Object,
    default: {}
  },
  type: {
    default: "",
    type: String
  }
})
const bwlist = ref([])
const showDept = ref(false)
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 aqbslist = ref([])
const memberList = ref([])
const zzlx = ref(null)
const addtype = ref("aqbs")
const csmclist = ref([])
const jzwlist = ref([])
const lclist = ref([])
onMounted(() => {
  addtype.value = props.formData.type ? props.formData.type : "aqbs"
  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.sfcq = props.formData.sfcq ? props.formData.sfcq : null
  fromData.value.publicarea = props.formData.publicarea ? props.formData.publicarea : 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
  getaqbslb()
  if (props.formData.id) {
    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 (["aqbs"].includes(addtype.value)) {
      getcsData()
    }
  }
})
// 生效时间只能选当天及之前的
const disabledDate = (time) => {
  return time.getTime() > Date.now()
}

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

// 获取相关方责任人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
}

//获取场所选择
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)
    }
  })
}

// (新)根据楼层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 getaqbslb() {
  getApi({
    zdbh: "D_TB_JCYWLX",
    dm: "2003",
    level: 2
  }, "/mosty-base/sysDict/getJcyelxDictTree").then(res => {
    aqbslist.value = res[0].itemList
  })
}

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

}

const getSonValue = (value) => {
  if (zzlx.value == "01") {
    fromData.value.responsibledeptname = value.orgName
    fromData.value.responsibledeptid = value.id
  } else {
    fromData.value.responsibleusername = value.map(item => {
      if (item.mobile) {
        return item.userName + "（" + item.mobile + "）"
      } else {
        return item.userName
      }

    }).toString()
    fromData.value.responsibleuserid = value.map(item => {
      return item.id
    }).toString()
  }

}

//关闭弹窗
const closezzjg = (val) => {
  showDept.value = val
}
// 保存
const submit = async (ruleFormRef) => {
  saveloading.value = true
  if (!ruleFormRef) return
  await ruleFormRef.validate((valid) => {
    if (valid) {
      ruleFormRef2.value.validate((valid) => {
        if (valid) {
          fromData.value.file = fromData.value.file ? fromData.value.file.toString() : null
          if (fromData.value) {
            if (!fromData.value.id) {
              postApi(fromData.value, "/mosty-jcgl/sitelogo/addTbSitelogoOne")
                .then((res) => {
                  ElMessage.success("新增成功")
                  emit("createPage", res)
                }).finally(() => {
                saveloading.value = false
              })
            } else {
              postApi(fromData.value, "/mosty-jcgl/sitelogo/updateTbSitelogoOne")
                .then((res) => {
                  ElMessage.success("修改成功")
                  emit("changePage")
                }).finally(() => {
                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/sitelogo/queryTbSitelogoById").then((res) => {
      if (res) {
        res.responsibleusername = res.responsibleusername ? res.responsibleusername.replace(/（null）/g, "") : ""
        fromData.value = res
        fromData.value.saveBtnShow = props.formData.saveBtnShow
        getlcxq(fromData.value.buildingid)
        if (props.formData.type == "cs") {
          getjzwlist(res.siteid)
        } else if (props.formData.type == "lc") {
          getbwdata(res.floorid)
        } else if (["aqbs"].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
            }
          })
        }

      }
    })
  }
}

//获取建筑物详情
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")
  }

}

function closeDialog() {
  // 关闭上一次的表单校验
  ruleFormRef.value.clearValidate()
  emit("changePage")
}


</script>

<style lang="scss" scoped>
.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 30px;
  flex-wrap: wrap;
  justify-content: space-between;
}

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

::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%;
}

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