<template>
  <div>
    <MOSTY.FromPage :title="formPageTitle" @closeDialog="closeDialog">
      <template #content>
        <MOSTY.Assort :title="'基础信息'" />
        <el-form :model="FromData" ref="ruleFormRef" label-position="right" :rules="rules" label-width="172px"
          :disabled="props.tcType == 'see'">
          <el-form-item label="设备名称:" prop="name">
            <el-input v-model="FromData.name" style="width: 337px" />
          </el-form-item>

          <!-- <el-form-item label="部位:" prop="bw">
            <inputBwCascader ref="bwTreeRef" style="width: 337px" />
             <inputCsBwTree />
          </el-form-item> -->

          <!-- 场所部位 start -->
          <el-form-item label="所属场所:" prop="sitename">
            <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>
          <!-- && 场区建筑物 -->
          <el-form-item :label="FromData.publicarea == '1' ? '所属场区:' : '所属建筑物:'" prop="buildingname">
            <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>
          <!-- && 楼层 != '1' -->
          <el-form-item label="所属楼层:" prop="floorname" v-if="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>
          <!-- && 部位 == '1' -->
          <el-form-item :label="FromData.publicarea == '1' ? '场区部位:' : '所属部位:'" prop="partname">
            <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>

          <!-- 场所部位 end -->

          <el-form-item label="品牌:" prop="brand">
            <el-input v-model="FromData.brand" style="width: 337px" />
          </el-form-item>
          <el-form-item label="型号:" prop="model">
            <el-input v-model="FromData.model" style="width: 337px" />
          </el-form-item>
          <el-form-item label="功率(千瓦):" prop="power">
            <!-- <el-input v-model="FromData.power" style="width: 337px" /> -->
            <el-input-number v-model="FromData.power" min="-0.0001" max="99999999" step="1" precision="2"
              style="width: 337px"></el-input-number>
          </el-form-item>
          <el-form-item label="状态:" prop="state">
            <el-select v-model="FromData.state" placeholder="请选择状态" style="width: 337px">
              <el-option v-for="item in D_BZ_SYSZT" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="单位:" prop="unit">
            <!-- <el-input v-model="FromData.unit" style="width: 337px" /> -->
            <MOSTY.DictRidioAndSelect :dictData="D_BZ_WPDW" v-model="FromData.unit" selectType="select"
              :disabled="tcType == 'see'" style="width: 337px" />
          </el-form-item>
          <el-form-item label="装置名称:" prop="devicename">
            <el-input v-model="FromData.devicename" style="width: 337px" />
          </el-form-item>
          <el-form-item label="装置数量:" prop="devicenum">
            <!-- <el-input v-model.number="FromData.devicenum" style="width: 337px" /> -->
            <el-input-number v-model="FromData.devicenum" min="-0.1" max="99999999" step="1" precision="0"
              style="width: 337px"></el-input-number>
          </el-form-item>
          <el-form-item label="厂家:" prop="manufactor">
            <el-input v-model="FromData.manufactor" style="width: 337px" />
          </el-form-item>
          <el-form-item label="购买时间:" prop="purchasetime">
            <el-date-picker style="width: 337px" v-model="FromData.purchasetime" value-format="YYYY-MM-DD"
              format="YYYY-MM-DD" type="date" placeholder="请选择时间"></el-date-picker>
          </el-form-item>
          <el-form-item label="出厂时间:" prop="factorytime">
            <el-date-picker style="width: 337px" v-model="FromData.factorytime" value-format="YYYY-MM-DD"
              format="YYYY-MM-DD" type="date" placeholder="请选择时间"></el-date-picker>
          </el-form-item>
          <el-form-item label="出厂编号:" prop="factoryno">
            <el-input v-model="FromData.factoryno" style="width: 337px" />
          </el-form-item>

          <el-form-item label="设备类型:" prop="sblx">
            <MOSTY.DictRidioAndSelect :dictData="D_TB_JCYWLX" v-model="FromData.sblx" selectType="select"
              :disabled="tcType == 'see'" style="width: 337px" />
            <!-- <MOSTY.DictTree v-model="fromObj.sblx" :zdlist="D_TB_JCYWLX" :placeholder='"请选择设备类型"'
              :disabled="tcType == 'see'" :type='"array"' style="width: 337px;" /> -->
          </el-form-item>
          <!-- <el-form-item label="投入金额(万元):" prop="money">
            <el-input v-model="FromData.money" style="width: 337px" />
          </el-form-item> -->
          <el-form-item label="安装时间:" prop="azsj">
            <el-date-picker style="width: 337px" v-model="FromData.azsj" value-format="YYYY-MM-DD" format="YYYY-MM-DD"
              type="date" placeholder="请选择时间"></el-date-picker>
          </el-form-item>
          <el-form-item label="接地情况:" prop="connectgroundinfo">
            <MOSTY.DictRidioAndSelect :dictData="D_BZ_SF" v-model="FromData.connectgroundinfo" selectType="select"
              :disabled="tcType == 'see'" style="width: 337px" />
          </el-form-item>
          <MOSTY.Assort :title="'管理信息'" />
          <br />
          <el-form-item label="责任部门:" prop="responsibilitydeptname">
            <inputDept :deptId="deptInputDept" v-model:ids="FromData.responsibilitydeptid"
              v-model:cName="FromData.responsibilitydeptname" :Single="true" width="337px" @change="deptChange">
            </inputDept>
          </el-form-item>
          <div style="width: 100%"></div>
          <el-form-item label="责任人:" prop="responsibilitypersonname">
            <inputUser type="textarea" :deptId="FromData.responsibilitydeptid"
              v-model:ids="FromData.responsibilityperson" :Single="false"
              v-model:cName="FromData.responsibilitypersonname" width="850px" @change="founderChange"></inputUser>
          </el-form-item>

          <!-- <el-form-item label="巡查相关方：" prop="xgfMc">
            <XiangGFSelect style="width: 337px" v-model="FromData.xgfMc" v-model:id="FromData.xgfId" />
          </el-form-item>
          <el-form-item label="相关方责任人：" prop="xgfRyMc">
            <XiangGFRen inputWidth="337px" v-model:ids="FromData.xgfRyId" v-model:cName="FromData.xgfRyMc"
              :relatedid="FromData.xgfId" :disabled="!FromData.xgfId" />
          </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="isShowdt = !isShowdt" />
            </div>
            <div v-show="isShowdt">
              <MOSTY.TabList :tablist="tablist2" type="sb" :obj="FromData" @handleChange="changelicolor2"
                @resetChange="searchChange" :isEdit="tcType != 'see'" />
            </div>
          </div>
        </div>
      </template>
      <template #dwbox> </template>
      <template #footer>
        <el-button type="primary" v-loading="saveloading" @click="saveData(ruleFormRef)" v-if="tcType != 'see'">
          <el-icon>
            <DocumentChecked />
          </el-icon>
          保存
        </el-button>
        <el-button @click="closeDialog()">
          <el-icon>
            <DocumentDelete />
          </el-icon>
          关闭
        </el-button>
      </template>
    </MOSTY.FromPage>
  </div>
</template>

<script setup>
import { getImgUrl } from '@/utils/tools.js'
import { ref, reactive, onMounted, defineAsyncComponent, getCurrentInstance } from 'vue'
import * as MOSTY from '@/components/MyComponents/index'
import { ElMessage } from 'element-plus'
import inputUser from '@/views/fxgk/jcss/components/MostCom/inputUser.vue'
import inputDept from '@/views/fxgk/jcss/components/MostCom/inputDept.vue'
import { Html2canvasImg } from '@/utils/html2pdf.js'
import XiangGFSelect from '@/components/dialog/component/XiangGFSelect.vue'
import XiangGFRen from '@/components/dialog/component/XiangGFRen.vue'
import * as rule from '@/utils/rules.js'
import { getItem } from '@/utils/storage'
import { getaqbm } from '@/api/sys.js'
import { postApi, getApi } from '@/api/tobAcco_api.js'
// import inputBwCascader from '../../../../components/inputCom/inputBwCascader.vue'
// import inputCsBwTree from '../../../../components/inputCom/inputCsBwTree.vue'

const { proxy } = getCurrentInstance()
/** 字典 */
const dict = proxy.$dict('D_BZ_SYSZT', 'D_BZ_SF', 'D_BZ_WPDW', 'D_TB_JCYWLX')
const { D_BZ_SYSZT, D_BZ_SF, D_BZ_WPDW, D_TB_JCYWLX } = dict

const emits = defineEmits('ok', 'close')
// 接收子组件传来的
const props = defineProps({
  id: {
    type: String,
    default: ''
  },
  row: {
    type: Object,
    default: {}
  },
  /** 弹窗类型 add edit see */
  tcType: {
    default: '',
    type: String
  }
})
const rules = {
  sitename: [{ required: true, message: '请选择所属场所', trigger: 'change' }],
  buildingname: [{ required: true, message: '请选择所属建筑物', trigger: 'change' }],
  floorname: [{ required: true, message: '请选择所属楼层', trigger: 'change' }],
  partname: [{ required: true, message: '请选择所属部位', trigger: 'change' }],
  responsibilitydeptname: [{ required: true, message: '请选择责任部门', trigger: 'change' }],
  responsibilitypersonname: [{ required: true, message: '请选择责任人', trigger: 'change' }]
}

const bwTreeRef = ref()

const deptInputDept = ref(getItem('deptId').ssdwid)
const formPageTitle = ref('')
const showDept = ref(false)
const showdwDept = ref(false)
const saveloading = ref(false)
const chooseUserVisible = ref(false) //选择领导弹窗
const singleShow = ref(true) //单选多选
const memberList = ref([])
const zzlx = ref(null)
const keys = ref(1)
const deptId = ref(null)
const deptIdbm = ref(null)
const isgetFrom = ref(false)
const Isstrictly = ref(false)
const ruleFormRef = ref()
const ruleFormRef2 = ref()
const isShowdt = ref(true)
const addtype = ref('scsbss')
const xgflist = ref([])
const isShowgd = ref(true)
const csmclist = ref([])
const jzwlist = ref([])
const lclist = ref([])
const bwlist = ref([])
/** 表单数据 */
const FromData = ref({})

// 01 安全装置 02 防护装置 03 保护装置 04 安全附件
const tablist1 = ref([])
const tablist = ref([])
const tablist2 = ref([
  {
    title: '检查标准',
    num: 0,
    icon: 'sbss2',
    sblx: '200500000000',
    actives: true,
    components: defineAsyncComponent(() => import('@/components/MyComponents/TabList/Synthesize.vue'))
  },
  {
    title: '检测记录',
    num: 0,
    icon: 'sbss2',
    actives: false,
    components: defineAsyncComponent(() => import('@/components/MyComponents/TabList/Testing.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'))
  },
  {
    title: '检查记录',
    num: 0,
    icon: 'sbss2',
    actives: false,
    components: defineAsyncComponent(() => import('@/components/MyComponents/TabList/Standard.vue'))
  }
])

// const addtype = ref("tzsb")
onMounted(() => {
  const tcType = props.tcType
  getcsData()
  if (tcType == 'add') {
    formPageTitle.value = '实验设备新增'
    FromData.value = {}
  } else if (tcType == 'edit') {
    formPageTitle.value = '实验设备修改'
    getmain(props.id)
    // FromData.value = props.row || {}
  } else if (tcType == 'see') {
    formPageTitle.value = '实验设备查看'
    getmain(props.id)
  }
})

function changexgf(val) {
  FromData.value.wborgcode = val.value
  FromData.value.wborgname = val.label
  FromData.value.phone = val.phone
}

function change(type) {
  switch (type) {
    case 'ccrq':
      FromData.value.azsj = ''
      FromData.value.trsysj = ''
      break
    case 'azsj':
      FromData.value.trsysj = ''
      break
    default:
      break
  }
}

// 获取相关方责任人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 deptChange = val => {
  // 清空责任人
  FromData.value.responsibilitypersonname = ''
  FromData.value.responsibilityperson = ''
}
const founderChange = val => {
  // FromData.value.responsibilitydeptname = val?.[0]?.deptName || ""
  // FromData.value.responsibilitydeptid = val?.[0]?.deptId || ""
}
function getxgflist() {
  let orgid = getItem('deptId').ssdwid || ''
  getApi({ orgid }, '/mosty-jcgl/relatedpartyinfo/getListByOrg').then(res => {
    if (res) {
      xgflist.value = res.map(item => {
        return {
          label: item.relatedname,
          value: item.id,
          phone: item.contactsphone
        }
      })
    }
  })
}

//安全装置总数
function getaqzzcount() {
  getApi({ zbid: props.formData.id }, '/mosty-jcgl/SbglAqzz/countTbSbglAqzz').then(res => {
    tablist1.value[1].num = res ? res : 0
  })
}

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

//获取场所选择
const cahngecsmc = val => {
  const currObj = csmclist.value.find(item => item.id == val)
  if (!currObj) return
  FromData.value.siteid = currObj.id
  FromData.value.sitename = currObj.placename
  FromData.value.buildingname = ''
  FromData.value.buildingid = ''
  FromData.value.publicarea = ''
  FromData.value.floorname = ''
  FromData.value.floorid = ''
  FromData.value.partname = ''
  FromData.value.partid = ''
  getjzwlist(currObj.id)
}

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

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

//获取建筑物名称
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 ChooesDdld(val) {
  zzlx.value = val
  memberList.value = []
  deptId.value = null
  Isstrictly.value = false
  deptIdbm.value = null
  if (val == '01') {
    //设备负责人：
    if (FromData.value.responsibilitydeptid) {
      deptId.value = FromData.value.responsibilitydeptid
      memberList.value = FromData.value.responsibilityperson ? FromData.value.responsibilityperson.split(',') : []
      singleShow.value = false
      chooseUserVisible.value = true
    } else {
      ElMessage.error('请先选择责任部门！!')
    }
  } else if (val == '02') {
    //使用单位：
    Isstrictly.value = true
    showdwDept.value = true
  } else {
    Isstrictly.value = false
    deptIdbm.value = FromData.value.userorgcode
    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 if (zzlx.value == '02') {
    FromData.value.userorgname = value.orgName
    FromData.value.userorgcode = value.id
    if (value.id) {
      getaqbm({ orgcode: value.id }).then(res => {
        FromData.value.aqorgname = res.orgName
        FromData.value.aqorgcode = res.id
      })
    }
  } else if (zzlx.value == '03') {
    FromData.value.aqorgname = value.orgName
    FromData.value.aqorgcode = value.id
  } else if (zzlx.value == '04') {
    FromData.value.aqusername = value[0].userName
    FromData.value.aquserid = value[0].id
  } else if (zzlx.value == '05') {
    FromData.value.responsibilitydeptname = value.orgName
    FromData.value.responsibilitydeptid = value.id
  }
}

//关闭弹窗
const closezzjg = val => {
  showDept.value = val
  showdwDept.value = false
}

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

//分类点击事件
function changelicolor(val) {
  tablist1.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 getmain(id) {
  postApi({}, `/mosty-jcgl/syssb/getInfo/${id}`).then(res => {
    res = res || {}
    FromData.value = { ...res }
    // if (bwTreeRef.value) bwTreeRef.value?.setVal?.(res)
    if (res.siteid) {
      getjzwlist(res.siteid, jzwArr => {
        // 建筑物
        const currBuild = jzwArr.find(item => item.id == res.buildingid)
        FromData.value.publicarea = currBuild.publicarea
        if (FromData.value.publicarea == '1') {
          if (res.buildingid) getbw2data(res.buildingid)
        } else {
          if (res.buildingid) getlcdata(res.buildingid)
        }
      })
      if (res.floorid) getbwdata(res.floorid)
    }
  })
}

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 saveData = async formEl => {
  if (!formEl) return
  await formEl.validate(valid => {
    if (valid) {
      if (props.tcType == 'add') {
        saveloading.value = true
        postApi(FromData.value, `/mosty-jcgl/syssb/add`)
          .then(res => {
            ElMessage.success('保存成功')
            emits('ok')
          })
          .finally(() => {
            saveloading.value = false
          })
      } else if (props.tcType === 'edit') {
        postApi(FromData.value, `/mosty-jcgl/syssb/edit`)
          .then(res => {
            ElMessage.success('修改成功')
            emits('ok')
          })
          .finally(() => {
            saveloading.value = false
          })
      }
    } else {
      ElMessage.error('请正确填写表单!')
    }
  })
}

//新增
function addData(obj, mosty) {
  postApi(obj, mosty)
    .then(res => {
      ElMessage.success('新增成功')
      // emits("saveSuccess", res)
      emits('createPage', res)
    })
    .finally(() => {
      saveloading.value = false
    })
}

//修改
function updataData(obj, mosty) {
  saveloading.value = true
  postApi(obj, mosty)
    .then(res => {
      ElMessage.success('修改成功')
      emits('saveSuccess')
    })
    .finally(() => {
      saveloading.value = false
    })
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog {
  --el-dialog-margin-top: 10vh !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;
}

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

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