<template>
  <div class="bigBox">
    <PageTitle :title="data.config.title">
      <el-button type="primary" @click="submit(ruleFormRef)" v-if="data.config.saveBtnShow">保存</el-button>
      <el-button @click="black">关闭</el-button>
    </PageTitle>
    <div class="box_cont">
      <div class="searchBox" ref="searchBox">
        <el-form class="mosty-from-wrap" ref="ruleFormRef" label-width="130px" :model="data.fromObj" :inline="true"
          :rules="rules" :disabled="!data.config.saveBtnShow">
          <el-form-item label="安防器材名称：" prop="equipmentname">
            <el-input v-model="data.fromObj.equipmentname" placeholder="请输入安防器材名称" clearable
              style="width: 250px"></el-input>
          </el-form-item>
          <el-form-item label="所属场所：" prop="placename">
            <el-select v-model="placename" @change="cahngecsmc" clearable style="width: 250px" 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="所属部位：" prop="allname">
            <el-select v-model="data.fromObj.allname" @change="cahngebw" clearable style="width: 250px"
              placeholder="请选择部位名称：">
              <el-option v-for="item in bwlist" :key="item" :label="item.allname" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="规格型号参数：">
            <el-input v-model="data.fromObj.modelparameter" placeholder="请输入型号规格参数" clearable
              style="width: 250px"></el-input>
          </el-form-item>
          <el-form-item label="采购时间：" prop="cgsj">
            <el-date-picker v-model="data.fromObj.purchasingtime" type="date" value-format="YYYY-MM-DD"
              style="width: 250px" placeholder="请选择采购时间" />
          </el-form-item>
          <el-form-item label="生产厂家：">
            <el-input v-model="data.fromObj.manufacturer" placeholder="请输入生产厂家" clearable
              style="width: 250px"></el-input>
          </el-form-item>
          <el-form-item label="器材数量：">
            <el-input-number controls-position="right" v-model="data.fromObj.equipmentcount" placeholder="请输入装置数量"
              clearable style="width: 250px"></el-input-number>
          </el-form-item>
          <el-form-item label="器材单位：" prop="qcdw">
            <el-select v-model="data.fromObj.equipmentunit" placeholder="请选择单位" clearable style="width: 250px">
              <el-option v-for="item in D_BZ_WPDW" :key="item.value" :label="item.label"
                :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="内部编号：">
            <el-input v-model="data.fromObj.nbbh" placeholder="请输入内部编号" clearable style="width: 250px"></el-input>
          </el-form-item>

          <el-form-item label="状态：" prop="zt">
            <el-select v-model="data.fromObj.zt" placeholder="请选择状态" clearable style="width: 250px">
              <el-option v-for="item in D_BZ_SBSSZT" :key="item.value" :label="item.label"
                :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <div class="ld_box">
            <el-form-item label="责任人：" prop="responsibilityusername">
              <el-input v-model="data.fromObj.responsibilityusername" clearable disabled style="width: 170px" />
            </el-form-item>
            <el-button type="primary" @click="ChooesDdld('01')">选择</el-button>
          </div>
          <el-form-item label="责任部门：" prop="responsibilitydeptname">
            <el-input v-model="data.fromObj.responsibilitydeptname" disabled clearable style="width: 250px" />
          </el-form-item>
          <el-form-item label="类型：" prop="type">
            <el-select v-model="data.fromObj.type" placeholder="请选择类型" style="width: 250px">
              <el-option v-for="item in D_BZ_AFQCLX" :key="item.value" :label="item.label"
                :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="检查标准：" prop="checkstandard">
            <el-select v-model="data.fromObj.checkstandard" placeholder="请选择检查标准" clearable style="width: 250px">
              <el-option v-for="item in D_TB_JCBZLB" :key="item.value" :label="item.label"
                :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="所在位置：">
            <el-input v-model="data.fromObj.location" placeholder="请输入所在位置" clearable style="width: 1220px"></el-input>
          </el-form-item>
          <el-form-item label="备注：" prop="bz">
            <el-input v-model="data.fromObj.bz" type="textarea" :rows="6" style="width: 1220px" show-word-limit
              maxlength="200" />
          </el-form-item>
          <el-collapse v-model="activeNames" style="width: 100%">
            <el-collapse-item title="安防器材二维码" name="1" v-if="data.fromObj.id">
              <el-form-item label="" label-width="30px !important">
                <MOSTY.ErwmImg
                  :url="qrcodeImg(data.fromObj.id, '414', placename, data.fromObj.allname, `${data.fromObj.equipmentname}(${data.fromObj.nbbh})`)"
                  :filename='"安防器材二维码"' :id="'htmlsmewmafqc'" />
              </el-form-item>
            </el-collapse-item>
            <el-collapse-item title="检测记录信息列表" name="2">
              <div class="mt7">
                <el-button class="addbtn" type="primary" @click="addjcinput">
                  <el-icon>
                    <CirclePlus />
                  </el-icon>
                  <span>新增</span>
                </el-button>
                <el-button class="addbtn" type="primary" @click="submitjctab">
                  <el-icon>
                    <Select />
                  </el-icon>
                  <span>保存</span>
                </el-button>
                <el-button class="addbtn" type="primary" @click="deletejctab">
                  <el-icon>
                    <DeleteFilled />
                  </el-icon>
                  <span>删除</span>
                </el-button>
              </div>
              <div class="tabbox">
                <el-table :data="data.fromObj.tbInspectionrecords" border stripe style="width: 100%"
                  :height="tableHeight" :key="keyCount" @row-click="handlecheckChange">
                  <!-- <el-table-column label="#" type="index" /> -->
                  <!-- <el-table-column prop="id" label="id"></el-table-column> -->
                  <el-table-column sortable prop="detectionmechanism" align="center" label="检测机构">
                    <template #default="{ row }">
                      <el-input v-if="row.input == true" type="text" v-model="row.detectionmechanism" />
                      <span v-else>{{ row.detectionmechanism }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column sortable prop="testdescription" label="检测描述">
                    <template #default="{ row }">
                      <el-input v-if="row.input == true" type="text" v-model="row.testdescription" />
                      <span v-else>{{ row.testdescription }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column sortable prop="expirationdate" align="center" label="有限期限">
                    <template #default="{ row }">
                      <el-date-picker v-if="row.input == true" v-model="row.expirationdate" style="width: 100%"
                        type="date" value-format="YYYY-MM-DD" />
                      <span v-else>{{ row.expirationdate }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column sortable prop="status" align="center" label="检测状态">
                    <template #default="{ row }">
                      <el-select v-if="row.input == true" v-model="row.status" style="width: 100%" clearable>
                        <el-option v-for="item in D_BZ_JCZT" :key="item" :label="item.label" :value="item.value" />
                      </el-select>
                      <dict-tag v-else :options="D_BZ_JCZT" :value="row.status" :tag="false" />
                    </template>
                  </el-table-column>
                  <el-table-column sortable prop="file" align="center" label="检测报告">
                    <template #default="scope">
                      <span class="operate" style="color: yellowgreen"
                        @click="handleChangefj(scope.$index, scope.row)">附件</span>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-collapse-item>
            <el-collapse-item title="维保记录列表" name="3" v-if="data.config.wbjlShow">
              <div class="mt7">
                <el-button class="addbtn" type="primary" @click="addwbinput">
                  <el-icon>
                    <CirclePlus />
                  </el-icon>
                  <span>新增</span>
                </el-button>
                <el-button class="addbtn" type="primary" @click="submitwbtab">
                  <el-icon>
                    <Select />
                  </el-icon>
                  <span>保存</span>
                </el-button>
                <el-button class="addbtn" type="primary" @click="deletewbtab">
                  <el-icon>
                    <DeleteFilled />
                  </el-icon>
                  <span>删除</span>
                </el-button>
              </div>
              <div class="tabbox">
                <el-table :data="data.fromObj.tbMaintenanceRecords" border stripe style="width: 100%"
                  :height="tableHeight" :key="keyCount" @row-click="handlewbChange">
                  <el-table-column sortable prop="maintenanceorg" align="center" label="维保单位">
                    <template #default="{ row }">
                      <el-input v-if="row.input == true" type="text" v-model="row.maintenanceorg" />
                      <span v-else>{{ row.maintenanceorg }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column sortable prop="maintenancepeople" label="维保人">
                    <template #default="{ row }">
                      <el-input v-if="row.input == true" type="text" v-model="row.maintenancepeople" />
                      <span v-else>{{ row.maintenancepeople }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column sortable prop="maintenancetel" label="维保电话">
                    <template #default="{ row }">
                      <el-input-number controls-position="right" v-if="row.input == true" type="text"
                        v-model="row.maintenancetel" />
                      <span v-else>{{ row.maintenancetel }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column sortable prop="maintenancedescription" label="维保描述">
                    <template #default="{ row }">
                      <el-input v-if="row.input == true" type="text" v-model="row.maintenancedescription" />
                      <span v-else>{{ row.maintenancedescription }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column sortable prop="maintenancetime" align="center" label="维保时间">
                    <template #default="{ row }">
                      <el-date-picker v-if="row.input == true" v-model="row.maintenancetime" style="width: 100%"
                        type="date" value-format="YYYY-MM-DD" />
                      <span v-else>{{ row.maintenancetime }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column sortable prop="bz" label="备注">
                    <template #default="{ row }">
                      <el-input v-if="row.input == true" type="text" v-model="row.bz" />
                      <span v-else>{{ row.bz }}</span>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-collapse-item>
            <el-collapse-item title="检查日志列表" name="4" v-if="data.config.jcrzShow">
              <div class="tabbox">
                <el-table :data="data.fromObj.tbTaskcheckLogs" border stripe style="width: 100%" :height="tableHeight"
                  :key="keyCount">
                  <el-table-column sortable prop="checkuser" align="center" label="检查人">
                  </el-table-column>
                  <el-table-column sortable prop="checktime" label="检查日期">
                  </el-table-column>
                  <el-table-column sortable prop="checkdescription" align="center" label="检查描述">
                  </el-table-column>
                  <el-table-column sortable prop="quantityofpitfall" align="center" label="隐患数量">
                  </el-table-column>
                </el-table>
              </div>
            </el-collapse-item>
          </el-collapse>
        </el-form>
      </div>
    </div>
    <!-- 附件弹出框 -->
    <MOSTY.FileTable v-model="dialogVisible" :fileId="fjidlist.fileId" @closedialog="closedialog" @savefile="savefile"
      :showBtn="data.config.saveBtnShow"></MOSTY.FileTable>
    <!-- 选择带队领导 -->
    <ChooseUser v-model="chooseUserVisible" :Single="singleShow" :data="memberList" :leaderid="leaderid"
      @choosedUsers="getSonValue"></ChooseUser>
    <Choosebm :formInfo="data.fromObj" :showDdld="showDept" @closezzjg="closeJhss" @listdata="getSonValue"
      :zzlx="zzlx" />
  </div>
</template>

<script setup>
import {
  reactive,
  ref,
  watchEffect,
  getCurrentInstance,
  onMounted,
  watch,
  nextTick
} from "vue";
import * as MOSTY from "@/components/MyComponents/index";
import PageTitle from "@/components/PageTitle/PageTitle.vue";
import Choosebm from "@/components/MyComponents/ChooseDept/index.vue";
import { ElMessage } from "element-plus";
import { getApi, deleteApi, putApi, postApi } from "@/api/tobAcco_api.js";
import ChooseUser from "@/components/MyComponents/ChooseUser/Leader.vue";
import { qrcodeImg, createAndClickLink } from "@/utils/tools.js";
import { Html2canvasImg } from "@/utils/html2pdf.js";
const { proxy } = getCurrentInstance();
const { D_BZ_WPDW } = proxy.$dict("D_BZ_WPDW");
const { D_BZ_SBSSZT } = proxy.$dict("D_BZ_SBSSZT");
const { D_TB_JCBZLB } = proxy.$dict("D_TB_JCBZLB");
const { D_BZ_AFQCLX } = proxy.$dict("D_BZ_AFQCLX");
const { D_BZ_JCZT } = proxy.$dict("D_BZ_JCZT");
const props = defineProps({
  editObj: {
    type: Object,
    default: () => { }
  }
});
const activeNames = ref(1);
const showDept = ref(false); //选择部门
const dialogVisible = ref(false);
const currentRowjc = ref(); //选中的表格数据
const chooseUserVisible = ref(false); //选择领导弹窗
const singleShow = ref(true); //单选多选
const memberList = ref([]); //成员选择的id回显
const leaderid = ref("");
const zzlx = ref(null);
const fileindex = ref(0);
const fjtableData = ref([]);
const bwlist = ref([]);
const fjidlist = reactive({});
const placename = ref("");
const emit = defineEmits("changePage");
const allname = ref("");
const ruleFormRef = ref();
const data = reactive({
  fromObj: {},
  config: {
    title: "",
    saveBtnShow: true,
    wbjlShow: false,
    jcrzShow: false
  }
});
//点击带队领导选择按钮
function ChooesDdld(val) {
  zzlx.value = val;
  leaderid.value = "";
  if (val == "01") {
    leaderid.value = data.fromObj.responsibilityperson;
    singleShow.value = true;
    chooseUserVisible.value = true;
  }
  if (val == "02") {
    leaderid.value = data.fromObj.safetyperid;
    singleShow.value = true;
    chooseUserVisible.value = true;
  }
  if (val == "03") {
    showDept.value = true;
  }
}

const getSonValue = (value) => {
  if (zzlx.value == "01") {
    data.fromObj.responsibilityusername = value[0].userName;
    data.fromObj.responsibilityuserid = value[0].id;
    data.fromObj.responsibilitydept = value[0].deptId;
    data.fromObj.responsibilitydeptname = value[0].deptName;
  }
  if (zzlx.value == "02") {
    data.fromObj.safetypername = value[0].userName;
    data.fromObj.safetyperid = value[0].id;
  }
  if (zzlx.value == "03") {
    data.fromObj.sybmbh = value.id;
    data.fromObj.sybmmc = value.orgName;
  }
};
// 新的文件上传返回
const changeFile = (data) => {
  if (data.length > 0 && data[0].response) {
    let arr = data.map((e) => {
      return e.raw;
    });
    fjtableData.value = arr;
  } else {
    fjtableData.value = data;
  }
};
//点击下载文件
function handledlon(val) {
  createAndClickLink(val.url, val.name);
}
//删除文件
const realFileslistdelete = (row) => {
  delrow.value = row;
  fjtableData.value = fjtableData.value.filter((item) => {
    return item != row;
  });
};
const savefile = (val) => {
  data.fromObj.tbInspectionrecords[fileindex.value].file = val.toString();
  dialogVisible.value = false;
};
function closedialog(val) {
  dialogVisible.value = val;
}
//新增检测记录表格
function addjcinput() {
  let tab = {
    detectionmechanism: "",
    testdescription: "",
    expirationdate: "",
    status: "",
    file: "",
    input: true
  };
  if (data.fromObj.tbInspectionrecords && data.fromObj.tbInspectionrecords.length) {
    let legths = data.fromObj.tbInspectionrecords.length - 1;
    let newdata = data.fromObj.tbInspectionrecords[legths];
    if (newdata.expirationdate != "" && newdata.status != "") {
      data.fromObj.tbInspectionrecords.push(tab)
    }
  } else {
    let arr = [];
    arr.push(tab);
    data.fromObj.tbInspectionrecords = arr;
  }
}
//保存表格数据
function submitjctab() {
  data.fromObj.tbInspectionrecords.forEach((el) => {
    el.input = false;
  });
}
//删除表格数据
function deletejctab() {
  data.fromObj.tbInspectionrecords.forEach((item, index) => {
    if (currentRowjc.value == item) {
      data.fromObj.tbInspectionrecords.splice(index, 1);
    }
  });
}
//选中当前表格行
function handlecheckChange(val) {
  currentRowjc.value = val;
  if (data.config.saveBtnShow) {
    data.fromObj.tbInspectionrecords.forEach((el) => {
      if (el == val) {
        el.input = true;
      } else {
        el.input = false;
      }
    });
  }
}
const currentRowwb = ref(); //选中的表格数据
//新增维保记录表格
function addwbinput() {
  let tab = {
    maintenanceorg: "",
    maintenancepeople: "",
    maintenancetel: "",
    maintenancedescription: "",
    maintenancetime: "",
    bz: "",
    input: true
  };
  if (data.fromObj.tbMaintenanceRecords) {
    data.fromObj.tbMaintenanceRecords.push(tab);
  } else {
    let arr = [];
    arr.push(tab);
    data.fromObj.tbMaintenanceRecords = arr;
  }
}
//保存表格数据
function submitwbtab() {
  data.fromObj.tbMaintenanceRecords.forEach((el) => {
    el.input = false;
  });
}
//删除表格数据
function deletewbtab() {
  data.fromObj.tbMaintenanceRecords.forEach((item, index) => {
    if (currentRowwb.value == item) {
      data.fromObj.tbMaintenanceRecords.splice(index, 1);
    }
  });
}
//选中当前表格行
function handlewbChange(val) {
  currentRowwb.value = val;
  data.fromObj.tbMaintenanceRecords.forEach((el) => {
    if (el == val) {
      el.input = true;
    } else {
      el.input = false;
    }
  });
}
//附件详情弹窗
function handleChangefj(index, row) {
  fjtableData.value = [];
  if (row.file) {
    fjidlist.fileId = row.file.split(",");
  } else {
    fjidlist.fileId = row.file;
  }
  fileindex.value = index;
  dialogVisible.value = true;
}
const rules = reactive({
  equipmentname: [
    { required: true, message: "请输入安防器材名称", trigger: "change" }
  ],
  placename: [{ required: true, message: "请选择所属场所", trigger: "change" }],
  type: [{ required: true, message: "请选择类型", trigger: "change" }],
  checkstandard: [{ required: true, message: "请选择检查标准", trigger: "change" }],
  allname: [{ required: true, message: "请选择所属部位", trigger: "blur" }],
  allname: [{ required: true, message: "请选择所属部位", trigger: "blur" }],
  responsibilityusername: [{ required: true, message: "请选择责任人", trigger: "blur" }],
  responsibilitydeptname: [{ required: true, message: "请选择责任部门", trigger: "blur" }]
});

// 保存
const submit = async (ruleFormRef) => {
  if (!ruleFormRef) return;
  await ruleFormRef.validate((valid) => {
    if (valid) {
      if (data.fromObj.tbInspectionrecords) {
        data.fromObj.tbInspectionrecords.forEach((e) => {
          if (e.file) {
            e.file = e.file.toString();
          }
        });
      } else {
        data.fromObj.tbInspectionrecords = [];
      }
      data.fromObj.tbMaintenanceRecords
        ? data.fromObj.tbMaintenanceRecords
        : (data.fromObj.tbMaintenanceRecords = []);
      data.fromObj.tbTaskcheckLogs
        ? data.fromObj.tbTaskcheckLogs
        : (data.fromObj.tbTaskcheckLogs = []);
      if (data.fromObj) {
        if (data.config.title == "新增") {
          postApi(
            data.fromObj,
            "/mosty-jcgl/securityEquipment/addTbSecurityEquipmentOne"
          )
            .then((res) => {
              ElMessage.success("新增成功");
              emit("changePage", "Main");
            })

        } else if (data.config.title == "编辑") {
          postApi(
            data.fromObj,
            "/mosty-jcgl/securityEquipment/updateTbSecurityEquipmentOne"
          )
            .then((res) => {
              ElMessage.success("修改成功");
              emit("changePage", "Main");
            })

        }
      }
    } else {
      ElMessage.error("请输入必填项!");
    }
  });
};
//获取详情
function getmain(id) {
  if (id) {
    getApi(
      { id: id },
      "/mosty-jcgl/securityEquipment/queryTbSecurityEquipmentById"
    ).then((res) => {
      if (res) {
        data.fromObj = JSON.parse(JSON.stringify(res));
        data.fromObj.allname = data.fromObj.partname;
        placename.value = data.fromObj.placename;
      }
    });
  }
}
const black = () => {
  if (data.config.saveBtnShow) {
    proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
      .then(() => {
        // 关闭上一次的表单校验
        ruleFormRef.value.clearValidate();
        emit("changePage", "Main");
      })
      .catch(() => {
        // catch error
      })
  } else {
    // 关闭上一次的表单校验
    ruleFormRef.value.clearValidate();
    emit("changePage", "Main");
  }

};
const csmclist = ref([]);
//根据操作人 查询 场所
function getcsData() {
  getApi({}, "/mosty-jcgl/site/getSiteListByUser").then((res) => {
    csmclist.value = res;
  });
}
//获取场所选择
const cahngecsmc = (val) => {
  csmclist.value.forEach((item) => {
    if (item.id == val) {
      data.fromObj.placeid = item.id;
      data.fromObj.placename = item.placename;
      getbwdata(item.id);
    }
  });
};
//根据操作人 获取部位信息
function getbwdata(id) {
  getApi({ partId: id }, "/mosty-jcgl/part/getpartListByUser").then((res) => {
    bwlist.value = res;
  });
}
//获取当前部位
const cahngebw = (val) => {
  bwlist.value.forEach((item) => {
    if (item.id == val) {
      data.fromObj.partid = item.id;
      data.fromObj.partname = item.areaname;
    }
  });
};
onMounted(() => {
  activeNames.value = ["1", "2", "3", "4"];
  getmain(props.editObj.id);
  getcsData();
});
watchEffect(() => {
  if (props.editObj) {
    data.config = JSON.parse(JSON.stringify(props.editObj));
  }
});
</script>

<style lang="scss" scoped>
.box_cont {
  height: calc(100vh - 15vh);
  overflow: auto;
}

.searchBox {
  width: 1200px;
  margin: 20px auto;
}

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



.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;
  padding: 0 14px;
  box-sizing: border-box;
}

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

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

.ld_box {
  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%;
}
</style>