<template>
  <div class="bigBox" :style="{ height: bigHeight }">
    <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="155px" :model="data.fromObj" :inline="true"
          :rules="rules" :disabled="!data.config.saveBtnShow">
          <el-form-item label="灭火器箱名称：" prop="name">
            <el-input v-model="data.fromObj.name" placeholder="请输入灭火器箱名称" style="width: 250px"></el-input>
          </el-form-item>
          <el-form-item label="型号规格参数：">
            <el-input v-model="data.extendattr.ext_xhggcs" placeholder="请输入型号规格参数" style="width: 250px"></el-input>
          </el-form-item>
          <el-form-item label="灭火器箱编号：">
            <el-input v-model="data.fromObj.ext_fireeqnum" placeholder="请输入灭火器箱编号" style="width: 250px"></el-input>
          </el-form-item>
          <el-form-item label="灭火器数量：">
            <el-input-number controls-position="right" v-model="data.extendattr.ext_devcount" placeholder="请输入灭火器数量"
              style="width: 250px"></el-input-number>
          </el-form-item>
          <el-form-item label="灭火器类别：" prop="extFireeqtypeid">
            <el-select v-model="data.fromObj.extFireeqtypeid" placeholder="请选择灭火器类别" @change="changemhq" clearable
              style="width: 250px">
              <el-option v-for="item in MHQFL" :key="item" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="投入金额(元)：">
            <el-input-number controls-position="right" v-model="data.fromObj.money" placeholder="请输入投入金额"
              style="width: 250px"></el-input-number>
          </el-form-item>
          <el-form-item label="安装日期：" prop="azsj">
            <el-date-picker v-model="data.fromObj.azsj" type="date" value-format="YYYY-MM-DD" placeholder="请选择安装日期"
              style="width: 250px" />
          </el-form-item>
          <el-form-item label="生产日期：" prop="cssj">
            <el-date-picker v-model="data.fromObj.cssj" type="date" value-format="YYYY-MM-DD" placeholder="请选择生产时间"
              style="width: 250px" />
          </el-form-item>
          <el-form-item label="采购时间：">
            <el-date-picker v-model="data.fromObj.cgsj" type="date" value-format="YYYY-MM-DD" placeholder="请选择采购时间"
              style="width: 250px" />
          </el-form-item>
          <el-form-item label="生产厂家：">
            <el-input v-model="data.extendattr.ext_sccj" placeholder="请输入生产厂家" style="width: 250px"></el-input>
          </el-form-item>
          <el-form-item label="场所名称：" prop="placename">
            <el-select v-model="data.fromObj.placename" @change="cahngecsmc" clearable placeholder="请选择场所名称："
              style="width: 250px">
              <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" style="width: 250px" clearable
              placeholder="请选择部位名称：">
              <el-option v-for="item in bwlist" :key="item" :label="item.allname" :value="item.id"
                style="width: 250px" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态：" prop="status">
            <el-select v-model="data.fromObj.status" placeholder="请选择状态" style="width: 250px">
              <el-option v-for="item in D_BZ_SBSSZT" :key="item" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <div class="ld_box">
            <el-form-item label="责任人：" prop="zrrname">
              <el-input v-model="data.fromObj.zrrname" disabled clearable style="width: 170px" />
            </el-form-item>
            <el-button type="primary" @click="ChooesDdld('01')">选择</el-button>
          </div>
          <el-form-item label="责任部门：" prop="zrbmname">
            <el-input v-model="data.fromObj.zrbmname" disabled clearable style="width: 250px" />
          </el-form-item>
          <div class="ld_box">
            <el-form-item label="灭火器编号：">
              <el-input v-model="data.extendattr.ext_fireeqnum" placeholder="请输入灭火器编号" style="width: 725px"></el-input>
            </el-form-item>
            <span style="color: red">(多个灭火器编号用逗号分隔)</span>
          </div>
          <el-form-item label="灭火器箱位置：">
            <el-input v-model="data.extendattr.ext_location" placeholder="请输入灭火器箱位置" style="width: 725px"></el-input>
          </el-form-item>

          <el-form-item label="备注：">
            <el-input v-model="data.extendattr.ext_bz" type="textarea" :rows="6" show-word-limit maxlength="200"
              style="width: 1000px" />
          </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, '413', data.fromObj.placename, data.fromObj.allname, `${data.fromObj.name}(${data.fromObj.ext_fireeqnum})`)"
                  :filename='"消防器材二维码"' :id="'htmlsmewmafqc'" />
              </el-form-item>
            </el-collapse-item>
            <el-collapse-item title="维保记录列表" name="2" v-if="data.config.wbjlShow">
              <div>
                <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>
        </el-form>
      </div>
    </div>
    <!-- 选择带队领导 -->
    <ChooseUser v-model="chooseUserVisible" :Single="singleShow" :data="memberList" :leaderid="leaderid"
      @choosedUsers="getSonValue"></ChooseUser>
  </div>
</template>

<script setup>
import {
  reactive,
  ref,
  watchEffect,
  getCurrentInstance,
  onMounted,
  watch,
  nextTick
} from "vue";
import * as MOSTY from "@/components/MyComponents/index";
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 PageTitle from "@/components/PageTitle/PageTitle.vue";
import * as rule from "@/utils/rules.js";
import { qrcodeImg } from "@/utils/tools.js";
import { Html2canvasImg } from "@/utils/html2pdf.js";
const { proxy } = getCurrentInstance();
const { MHQFL } = proxy.$dict("MHQFL"); //灭火器类别
const { D_BZ_SBSSZT } = proxy.$dict("D_BZ_SBSSZT");
const props = defineProps({
  saveBtnShow: {
    type: Boolean,
    default: true
  },
  editObj: {
    type: Object,
    default: () => { }
  }
});
const fromObj = ref({});
const dialogVisible = ref(false);
const activeNames = ref(["1"]);
const emit = defineEmits("changePage");
const ruleFormRef = ref();
const data = reactive({
  fromObj: {},
  extendattr: {},
  config: {
    title: "",
    saveBtnShow: true,
    wbjlShow: false,
    jcrzShow: false
  }
});
//点击带队领导选择按钮
const chooseUserVisible = ref(false); //选择领导弹窗
const singleShow = ref(true); //单选多选
const leaderid = ref("");
const zzlx = ref(null);
function ChooesDdld(val) {
  zzlx.value = val;
  leaderid.value = "";
  if (val == "01") {
    leaderid.value = data.fromObj.zrrid;
  }
  singleShow.value = true;
  chooseUserVisible.value = true;
}

const getSonValue = (value) => {
  if (zzlx.value == "01") {
    data.fromObj.zrrname = value[0].userName;
    data.fromObj.zrrid = value[0].id;
    data.fromObj.zrbmname = value[0].deptName;
    data.fromObj.zrbmcode = value[0].deptId;
  }
};

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;
  if (data.config.saveBtnShow) {
    data.fromObj.tbMaintenanceRecords.forEach((el) => {
      if (el == val) {
        el.input = true;
      } else {
        el.input = false;
      }
    });
  }
}
//新增
function addInfo() {
  fromObj.value = {};
  dialogVisible.value = true;
  data.title = "附件新增";
}
const current = ref();
//修改
function editInfo(row) {
  current.value = row.$index;
  fromObj.value = row.row;
  dialogVisible.value = true;
  data.title = "附件修改";
}
//删除
function delInfo(row) {
  data.fromObj.tbEquipmentAnnexes.forEach((item, index) => {
    if (row == item) {
      data.fromObj.tbEquipmentAnnexes.splice(index, 1);
    }
  });
}
//新增修改完毕
const submitry = () => {
  if (data.title == "附件新增") {
    if (data.fromObj.tbEquipmentAnnexes) {
      data.fromObj.tbEquipmentAnnexes.push(fromObj.value);
      dialogVisible.value = false;
    } else {
      let arr = [];
      arr.push(fromObj.value);
      data.fromObj.tbEquipmentAnnexes = arr;
      dialogVisible.value = false;
    }
  }
  if (data.title == "附件修改") {
    data.fromObj.tbEquipmentAnnexes[current.value] = fromObj.value;
    dialogVisible.value = false;
  }
};
const rules = reactive({
  name: [{ required: true, message: "请输入灭火器名称", trigger: "change" }],
  ggxh: [{ required: true, message: "请输入规格型号参数", trigger: "change" }],
  mhqxbh: [
    { required: true, message: "请输入灭火器箱编号", trigger: "change" }
  ],
  mhqsl: [{ required: true, message: "请输入灭火器数量", trigger: "change" }],
  extFireeqtypeid: [{ required: true, message: "请选择灭火器类别", trigger: "change" }],
  mhqbh: [{ required: true, message: "请输入灭火器编号", trigger: "change" }],
  cssj: [{ required: true, message: "请选择生产日期", trigger: "change" }],
  azsj: [{ required: true, message: "请选择安装日期", trigger: "change" }],
  placename: [{ required: true, message: "请选择所属场所", trigger: "change" }],
  allname: [{ required: true, message: "请选择所属部位", trigger: "change" }],
  status: [{ required: true, message: "请选择状态", trigger: "change" }],
  zrrname: [{ required: true, message: "请选择责任人", trigger: "change" }],
  zrbmname: [{ required: true, message: "请选择责任部门", trigger: "change" }]
});

// 保存
const submit = async (ruleFormRef) => {
  if (!ruleFormRef) return;
  await ruleFormRef.validate((valid) => {
    if (valid) {
      if (data.fromObj) {
        const arr = Object.entries(data.extendattr).map(([key, value]) => ({
          name: key,
          value
        }));
        data.fromObj.catalogid = "416";
        data.fromObj.extendattr = arr ? JSON.stringify(arr) : "";

        if (data.config.title == "新增") {
          postApi(data.fromObj, "/mosty-jcgl/equipment/addEquipmentOne")
            .then((res) => {
              ElMessage.success("新增成功");
              emit("changePage", "Main");
            })

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

        }
      }
    } else {
      ElMessage.error("请输入必填项!");
    }
  });
};

const placename = ref("");
const allname = ref("");
//获取详情
function getmain(id) {
  if (id) {
    getApi({ id: id }, "/mosty-jcgl/equipment/queryEquipmentById").then(
      (res) => {
        if (res) {
          data.fromObj = res;
          let arr = JSON.parse(data.fromObj.extendattr);
          data.extendattr = arr.reduce((acc, cur) => {
            acc[cur.name] = cur.value;
            return acc;
          }, {});
          data.fromObj.allname = data.fromObj.partname;
          data.fromObj.placename = data.fromObj.sitename;
        }
      }
    );
  }
}
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 extFireeqtypeid = ref("");
const csmclist = ref([]);
const bwlist = 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.siteid = item.id;
      data.fromObj.sitename = item.placename;
      getbwdata(item.id);
    }
  });
};
//获取灭火器类别选择
const changemhq = (val) => {
  // MHQFL.value.forEach((item) => {
  //   if (item.value == val) {
  //     data.fromObj.ext_fireeqtypeid = item.value;
  //     data.fromObj.ext_fireeqtypename = item.label;
  //   }
  // });
};
//根据操作人 获取部位信息
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>
::-webkit-scrollbar {
  width: 0 !important;
  height: 0;
}

.box_cont {
  height: calc(100vh - 15vh);
  overflow-y: scroll;
}

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

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



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

::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>