<template>
  <div class="bigBox" :style="{ height: bigHeight }">
    <MOSTY.FromPage :title="props.title" @closeDialog="CloseEvent">
      <template #content>
        <MOSTY.Assort :title="'基本信息'" />
        <div class="box_cont">
          <div class="fromBox">
            <div class="box_gbig">
              <div class="box_left">
                <el-form class="mosty-from-wrap" ref="ruleFormRef" label-width="141px" :model="data.fromObj"
                  :inline="true" :disabled="!props.saveBtnShow" :rules="rules">
                  <el-form-item v-if="data.fromObj.type === '01'" label="危险作业场所类别:" prop="cslb">
                    <el-radio-group v-model="data.fromObj.cslb" style="width:337px">
                      <el-radio label="01">场所</el-radio>
                      <el-radio label="02">设备</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <!-- <el-divider></el-divider> -->
                  <!-- 厂区部位 -->
                  <el-form-item label="所属场所:" prop="sitename" v-if="['cs', 'jzw', 'lc', 'bw'].includes(addtype)">
                    <el-input v-model="data.fromObj.sitename" style="width: 337px" disabled />
                  </el-form-item>
                  <el-form-item label="所属场所:" prop="sitename" v-if="['aqbs'].includes(addtype) && data.fromObj.id">
                    <el-input v-model="data.fromObj.sitename" style="width: 337px" disabled />
                  </el-form-item>
                  <el-form-item label="所属场所:" prop="sitename" v-if="['aqbs'].includes(addtype) && !data.fromObj.id">
                    <el-select v-model="data.fromObj.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>
                  <el-form-item :label="data.fromObj.publicarea == '1' ? '所属场区:' : '所属建筑物:'" prop="buildingname"
                    v-if="['cs', 'aqbs'].includes(addtype) && !data.fromObj.id">
                    <el-select v-model="data.fromObj.buildingname" @change="cahngejzwmc" clearable style="width: 337px"
                      :placeholder="data.fromObj.publicarea == '1' ? '请选择所属场区:' : '请选择所属建筑物:'">
                      <el-option v-for="item in jzwlist" :key="item" :label="item.buildingname" :value="item.id" />
                    </el-select>
                  </el-form-item>
                  <el-form-item :label="data.fromObj.publicarea == '1' ? '所属场区:' : '所属建筑物:'" prop="buildingname"
                    v-if="['cs', 'jzw', 'lc', 'bw', 'aqbs'].includes(addtype) && data.fromObj.id">
                    <el-input v-model="data.fromObj.buildingname" disabled style="width: 337px" />
                  </el-form-item>
                  <el-form-item :label="data.fromObj.publicarea == '1' ? '所属场区:' : '所属建筑物:'" prop="buildingname"
                    v-if="['jzw', 'lc', 'bw'].includes(addtype) && !data.fromObj.id">
                    <el-input v-model="data.fromObj.buildingname" disabled style="width: 337px" />
                  </el-form-item>
                  <el-form-item label="所属楼层:" prop="floorname"
                    v-if="['cs', 'jzw', 'aqbs'].includes(addtype) && data.fromObj.publicarea != '1' && !data.fromObj.id">
                    <el-select v-model="data.fromObj.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>
                  <el-form-item label="所属楼层:" prop="floorname"
                    v-if="['cs', 'jzw', 'lc', 'bw', 'aqbs'].includes(addtype) && data.fromObj.id && data.fromObj.publicarea != '1'">
                    <el-input v-model.number="data.fromObj.floorname" style="width: 337px" disabled />
                  </el-form-item>
                  <el-form-item label="所属楼层:" prop="floorname"
                    v-if="['lc', 'bw'].includes(addtype) && !data.fromObj.id && data.fromObj.publicarea != '1'">
                    <el-input v-model.number="data.fromObj.floorname" style="width: 337px" disabled />
                  </el-form-item>
                  <el-form-item :label="data.fromObj.publicarea == '1' ? '场区部位:' : '所属部位:'" prop="partname"
                    v-if="['cs', 'jzw', 'lc', 'aqbs'].includes(addtype) && !data.fromObj.id">
                    <el-select v-model="data.fromObj.partname" @change="cahngebw" clearable style="width: 337px"
                      :placeholder="data.fromObj.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="data.fromObj.publicarea == '1' ? '场区部位:' : '所属部位:'" prop="partname"
                    v-if="['bw'].includes(addtype) && !data.fromObj.id">
                    <el-input v-model="data.fromObj.partname" disabled style="width: 337px" />
                  </el-form-item>
                  <el-form-item :label="data.fromObj.publicarea == '1' ? '场区部位:' : '所属部位:'" prop="partname" v-if="['cs', 'jzw', 'lc', 'bw', 'aqbs'].includes(addtype)
                    && data.fromObj.id">
                    <el-input v-model="data.fromObj.partname" disabled style="width: 337px" />
                  </el-form-item>



                  <!-- 有限空间 -->
                  <template v-if="data.fromObj.type === '01'">
                    <el-form-item label="有限空间事故类别:" prop="spaceAccidentType">
                      <el-select v-model="data.fromObj.spaceAccidentType" style="width: 337px" clearable>
                        <el-option v-for="item in D_BZ_KNZCDSGLB" :key="item" :label="item.label" :value="item.value" />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="有限空间类别:" prop="spaceType">
                      <el-select v-model="data.fromObj.spaceType" style="width: 337px" clearable>
                        <el-option v-for="item in D_BZ_YXKJLB" :key="item" :label="item.label" :value="item.value" />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="危害因素:" prop="spaceHazardFactors">
                      <el-select v-model="data.fromObj.spaceHazardFactors" style="width: 337px" clearable
                        :multiple="true">
                        <el-option v-for="item in D_TB_YHWHYS" :key="item" :label="item.label" :value="item.value" />
                      </el-select>
                    </el-form-item>
                  </template>


                  <!-- 熏蒸杀虫 -->
                  <template v-if="data.fromObj.type === '02'">
                    <el-form-item label="作业人员数:" prop="stiflePeopleCount">
                      <el-input v-model="data.fromObj.stiflePeopleCount" @keyup="peopleCountInput" clearable
                        style="width: 337px" />
                    </el-form-item>
                    <el-form-item label="作业周期:" prop="stifleRate">
                      <el-select v-model="data.fromObj.stifleRate" style="width: 337px" clearable>
                        <el-option v-for="item in D_BZ_XSCZYZQ" :key="item" :label="item.label" :value="item.value" />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="熏蒸方式:" prop="stifleWay">
                      <el-select v-model="data.fromObj.stifleWay" style="width: 337px" clearable>
                        <el-option v-for="item in D_BZ_XZFS" :key="item" :label="item.label" :value="item.value" />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="相关方:" prop="stifleRelatedName">
                      <el-select v-model="data.fromObj.stifleRelatedName" style="width: 337px" @change="changexgf"
                        clearable placeholder="请选择相关方">
                        <el-option v-for="item in xgflist" :key="item.id" :label="item.label" :value="item" />
                      </el-select>
                    </el-form-item>
                  </template>



                  <!-- 场所 -->
                  <el-form-item v-if="data.fromObj.cslb === '01'" label="危险作业场所名称:" prop="name">
                    <el-input v-model="data.fromObj.name" clearable style="width: 337px" />
                  </el-form-item>
                  <!-- 设备 -->
                  <el-form-item v-if="data.fromObj.cslb === '02'" label="设备类型:" prop="sblx">
                    <el-select v-model="data.fromObj.sblx" style="width: 337px" clearable>
                      <el-option v-for="item in D_BZ_WXZYCSSBLX" :key="item" :label="item.label" :value="item.value" />
                    </el-select>
                  </el-form-item>
                  <el-form-item v-if="data.fromObj.cslb === '02'" label="设备名称:" prop="sbmc">
                    <equipment ref="equipmentRef" v-model="data.fromObj.sbid" :inputName="data.fromObj.sbmc"
                      :sblx="data.fromObj.sblx" :partid="data.fromObj.partid" :type="data.fromObj.type"
                      @ok="changeEquipment" style="width: 337px" />
                  </el-form-item>

                </el-form>


              </div>

            </div>
          </div>
        </div>


      </template>
      <template #footer>

        <el-button style="margin-left: 10px" type="primary" @click="handleSave(ruleFormRef)" v-if="props.saveBtnShow"
          :loading="saveloading">
          <el-icon>
            <DocumentChecked />
          </el-icon>
          <span>保存</span>
        </el-button>

        <el-button type="primary" @click="CloseEvent">
          <el-icon>
            <DocumentDelete />
          </el-icon>
          <span>关闭</span>
        </el-button>
      </template>
    </MOSTY.FromPage>

  </div>
</template>

<script setup>
import { getImgUrl } from "@/utils/tools.js"
import { ref, onMounted, defineProps, defineEmits, reactive, watch, getCurrentInstance, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { getItem } from "@/utils/storage";
import * as MOSTY from "@/components/MyComponents/index";
import { getApi, postApi } from "@/api/tobAcco_api.js";
import * as rule from "@/utils/rules.js";
const isaddtr = ref(true)
const { proxy } = getCurrentInstance();
import equipment from "./equipment/index.vue";
const { D_BZ_WXZYCSLX, D_BZ_XZFS, D_BZ_WXZYCSSBLX, D_BZ_XSCZYZQ, D_BZ_YXKJLB, D_BZ_KNZCDSGLB, D_BZ_WXZYJB, D_TB_YHWHYS } =
  proxy.$dict("D_BZ_WXZYCSLX", "D_BZ_XZFS", "D_BZ_WXZYCSSBLX", "D_BZ_XSCZYZQ",
    "D_BZ_YXKJLB", "D_BZ_KNZCDSGLB", "D_BZ_WXZYJB", "D_TB_YHWHYS");

const rules = reactive({
  // type: [{ required: true, message: "", trigger: "blur" }],
  cslb: [{ required: true, message: "危险作业场所类别不能为空", trigger: "change" }],
  sitename: [{ required: true, message: "场所名称不能为空", trigger: "change" }],
  partname: [{ required: true, message: "所属部位名称不能为空", trigger: "change" }],
  stifleRelatedName: [{ required: true, message: "相关方不能为空", trigger: "change" }],
  ...rule.numberzzsRule({ validator: true, require: true, num: 99999 }, "stiflePeopleCount"),
  stifleRate: [{ required: true, message: "作业周期不能为空", trigger: "change" }],
  stifleWay: [{ required: true, message: "熏蒸方式不能为空", trigger: "change" }],
  spaceAccidentType: [{ required: true, message: "有限空间事故类别不能为空", trigger: "change" }],
  spaceHazardFactors: [{ required: true, message: "有限空间危害因素不能为空", trigger: "change" }],
  spaceType: [{ required: true, message: "有限空间类别不能为空", trigger: "change" }],
  sbmc: [{ required: true, message: "设备名称不能为空", trigger: "change" }],
  name: [{ required: true, message: "危险作业场所名称不能为空", trigger: "change" }],
  sblx: [{ required: true, message: "设备类型不能为空", trigger: "change" }],
  floorname: [{ required: true, message: "所属楼层名称不能为空", trigger: "change" }],
  buildingname: [{ required: true, message: "所属建筑物名称不能为空", trigger: "change" }],

});
const equipmentRef = ref(null)
const saveloading = ref(false)
const props = defineProps({
  title: {
    type: String,
    default: ""
  },

  saveBtnShow: {
    type: Boolean,
    default: true
  },
  editObj: {
    type: Object,
    default: () => { }
  },
  zdlist: {
    type: Object,
    default: () => { }
  },
  /** 危险作业场所类型 01-有限空间 02-熏蒸杀虫 */
  type: {
    type: String,
    default: '01'
  }
});
const placename = ref("");
const emergency = ref("");
const activeNames = ref(1);
/**相关方option */
const xgflist = ref([])
const emits = defineEmits(["close"]);
const currentRowjc = ref(); //选中的表格数据
const spaceHazardFactors = ref()
const CloseEvent = () => {
  if (props.saveBtnShow) {
    proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
      .then(() => {
        // 关闭上一次的表单校验
        ruleFormRef.value.clearValidate();
        emits("close");
      })
      .catch(() => {
        // catch error
      })
  } else {
    // 关闭上一次的表单校验
    ruleFormRef.value.clearValidate();
    emits("close");
  }

};
const delrow = ref({}); //删除文件列表
const singleShow = ref(true); //单选多选
// const aqbslist = ref([])
const zzlx = ref(null);
const addtype = ref('aqbs')
const csmclist = ref([]);
/** 所属厂区，建筑物列表 */
const jzwlist = ref([])
const lclist = ref([]);
/** 厂区部位，所属部位 */
const bwlist = ref([]);
/** 获取相关方list */
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 }
      });
    }

  })
}
// 初始化
onMounted(() => {
  if (props.type == '02') data.fromObj.cslb = '01' // 熏蒸杀虫只有场所
  data.fromObj.type = props.type // 危险作业场所类型 01-有限空间 02-熏蒸杀虫
  getxgflist()
  if (props.editObj && props.editObj.id) {
    getmain(props.editObj.id);
  } else {
    if (props.editObj.type == 'cs') {
      getjzwlist(props.editObj.siteid)
    } else if (props.editObj.type == 'jzw') {
      if (props.editObj.publicarea == '1') {
        getbw2data(props.editObj.buildingid);
      } else {
        getlcdata(props.editObj.buildingid);
      }
    } else if (props.editObj.type == 'lc') {
      getbwdata(props.editObj.floorid);
    } else if (['aqbs'].includes(addtype.value)) {
      getcsData();
    }
  }
});
const peopleCountInput = (val) => {
  if (data.fromObj.stiflePeopleCount) {
    data.fromObj.stiflePeopleCount = data.fromObj.stiflePeopleCount.replace(/[^\d]/g, '')
  }
}
function changexgf(val) {
  data.fromObj.stifleRelatedId = val.value
  data.fromObj.stifleRelatedName = val.label
}
//获取详情
function getmain(id) {
  if (id) {
    getApi({ id: id }, "/mosty-jcgl/hazardousSite/getInfo").then((res) => {
      if (res) {
        data.fromObj = res;
        data.fromObj.saveBtnShow = props.editObj.saveBtnShow;
        data.fromObj.spaceHazardFactors = res.spaceHazardFactors.split(',')
        nextTick(() => {
          if (equipmentRef.value) equipmentRef.value.init({ inputName: res.sbmc, selectId: res.sbid })
        })
        if (props.editObj.type == 'cs') {
          getjzwlist(res.siteid)
        } else if (props.editObj.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) {
              data.fromObj.partname = res.partname ? res.partname : res.qtmc;
            }
          })
        }

      }
    });
  }
}
/** 数据 */
const data = reactive({
  fromObj: {
    type: props.type, // 危险作业场所类型 01-有限空间 02-熏蒸杀虫
    cslb: '01', // 危险作业场所类别 01-场所 02-设备 // 熏蒸杀虫只有场所。 默认为01
  }
});


watch(props.editObj, (newVal) => {
  if (newVal) {
    data.fromObj = props.editObj;
    placename.value = data.fromObj.placename;
  } else {
    data.fromObj = {};
    data.fromObj.tbBuildpeopleList = [];
  }
})

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

  data.fromObj.sbid = val.sbid
  data.fromObj.sbmc = val.sbmc
}
//获取场所选择
const cahngecsmc = (val) => {
  csmclist.value.forEach((item) => {
    if (item.id == val) {
      data.fromObj.siteid = item.id;
      data.fromObj.sitename = item.placename;
      data.fromObj.buildingname = '';
      data.fromObj.buildingid = '';
      data.fromObj.publicarea = '';
      data.fromObj.floorname = '';
      data.fromObj.floorid = '';
      data.fromObj.partname = '';
      data.fromObj.partid = '';


      getjzwlist(item.id)

    }
  });
};

//获取当前部位
const cahngebw = (val) => {
  bwlist.value.forEach((item) => {
    if (item.id == val) {
      data.fromObj.partid = item.id;
      data.fromObj.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) {
      data.fromObj.buildingid = item.id;
      data.fromObj.buildingname = item.buildingname;
      data.fromObj.publicarea = item.publicarea;
      data.fromObj.floorname = '';
      data.fromObj.floorid = '';
      data.fromObj.partname = '';
      data.fromObj.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) {
      data.fromObj.floorid = item.id;
      data.fromObj.floorname = item.floorname;
      data.fromObj.partname = '';
      data.fromObj.partid = '';
      getbwdata(item.id);
    }
  });
}
// (新)根据楼层id查询【部位】
function getbwdata(id) {
  // 原来/mosty-jcgl/part/getListByFloorid
  if (!data.fromObj.cslb) {
    bwlist.value = []
    return // =========== return ===========
  }
  getApi({ id, cslb: data.fromObj.cslb, type: props.type }, "/mosty-jcgl/hazardousSite/getPartList").then((res) => {
    bwlist.value = res ? res : [];
  });
}
//(新)根据建筑物id查询部位
function getbw2data(id) {
  getApi({ id }, "/mosty-jcgl/part/getListByBuildid").then((res) => {
    bwlist.value = res ? res : [];
  });
}

const leaderid = ref("");

//完成选人
const getSonValue = (value) => {
  if (zzlx.value == "2") {
    data.fromObj.fgldname = value[0].userName;
    data.fromObj.fgldid = value[0].id;
    data.fromObj.fglddeptname = value[0].deptName;
    data.fromObj.fglddeptid = value[0].deptId;
  }
  if (zzlx.value == "3") {
    data.fromObj.branchedleadname = value[0].userName;
    data.fromObj.branchedleadid = value[0].id;
    data.fromObj.branchedleaddeptname = value[0].deptName;
    data.fromObj.branchedleaddeptid = value[0].deptId;
  }
  if (zzlx.value == "4") {
    data.fromObj.managername = value[0].userName;
    data.fromObj.managerid = value[0].id;
    data.fromObj.managerdeptname = value[0].deptName;
    data.fromObj.managerdeptid = value[0].deptId;
  }
  examine();
};
//确认审核结果并且发起审核
function examine() {
  data.fromObj.ywid = data.fromObj.id;
  data.fromObj.file = data.fromObj.file ? data.fromObj.file.toString() : "";
  postApi(data.fromObj, "/mosty-jcgl/wxzy/approveWxzy").then(() => {
    ElMessage.success("修改审核状态成功");
    changestate();
  })
}

const ruleFormRef = ref();
// 保存
const handleSave = async (ruleFormRef) => {
  if (!ruleFormRef) return;
  await ruleFormRef.validate((valid) => {
    if (valid) {
      if (!data.fromObj) return
      // saveloading.value = true
      data.fromObj.spaceHazardFactors = Array.isArray(data.fromObj.spaceHazardFactors) ? data.fromObj.spaceHazardFactors.join(',') : null;
      if (data.fromObj.id) {
        postApi(data.fromObj, "/mosty-jcgl/hazardousSite/editSite").then((res) => {
          ElMessage.success("修改成功");
          emits("close");
        }).finally(() => {
          saveloading.value = false
        })

      } else {
        postApi(data.fromObj, "/mosty-jcgl/hazardousSite/addSite").then((res) => {
          ElMessage.success("新增成功");
          emits("close");
        }).finally(() => {
          saveloading.value = false
        })
      }
    } else {
      ElMessage.error("请输入必填项");
    }
  });
};
</script>

<style lang="scss" scoped>
.box_cont {
  height: 73vh;
  overflow-y: scroll;
}

.fromBox {
  // width: 1333px;
  margin: 20px auto;
  padding: 0 40px;
}

.box_gbig {
  width: 100%;
  display: flex;
  justify-content: center;
}

.ld_box {
  display: flex;
  margin-right: 30px;
}

.box_left {
  width: 856px;
}

.el-form {
  width: 100%;
  align-items: center;
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}

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

.addbtn {
  margin-bottom: 10px;
}

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

.tabbox {
  max-height: 300px;
  overflow-y: scroll;

  .input {
    width: 100%;
    height: 100%;
  }
}

::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;
    margin-bottom: 14px;
  }
}

::v-deep .el-upload-list {
  width: 50%;
}

::v-deep .el-table td.el-table__cell div {
  width: 100%;
}

//时间轴
.box_right {
  width: 37%;
  position: relative;
}

.box_right .line {
  position: absolute;
  top: 0;
  left: 201px;
  width: 1px;
  background-color: #5ecb4c;
  height: 420px;
  z-index: 10;
}

.typ {
  color: #5ecb4c;
  margin-right: 10px;
}

.timeimg {
  width: 100%;
  text-align: center;
}

.boc_tim {
  width: 60px;
  margin-left: 90px !important;
  height: 60px;
  background-color: #fff;
  z-index: 999;
}

.box_right ul li {
  color: #000;
  display: flex;
  padding: 0 20px;
  margin: 20px 0;
  z-index: 99;
  padding-left: 80px;
}

.box_right ul li div {
  margin: 0 20px;
}

.iconre {
  width: 20px;
  height: 20px;
  z-index: 99;
  margin-left: -10px;
}

.time_le span {
  display: block;
  width: 80px;
}
</style>
