<template>
  <div>
    <MOSTY.FromPage :title="'隐患治理'" @closeDialog="CloseEvent">
      <template #content>
        <div class="flex align-start ">
          <div style="color: #333" class="box_cont">
            <el-form class="mosty-from-wrap" ref="ruleFormRef" :model="formData" :inline="true" label-width="120px"
              :rules="rules">
              <el-collapse v-model="activeNames" @change="handleChange">
                <el-collapse-item v-show="!isBatch" title="隐患信息" name="1">
                  <div class="searchBox">
                    <div style="width:100%;padding:10px 20px">
                      <MOSTY.Upload v-if="formData.pics" :width="'100%'" :limit="5" :nopicer="false" :isImg="true"
                        :ShowfileList="false" :disabled='true' v-model="formData.pics">
                      </MOSTY.Upload>
                      <!-- <el-image v-if="formData.src" :src="formData.src" fit="scale-down" /> -->
                      <img v-else :src="getImgUrl('indexImages/zwtp.jpg')" alt=""
                        style="height:100%;width:auto;border:1px solid #ccc">
                    </div>
                    <el-form-item label="检查单位:">
                      <el-input v-model="formData.founderOrgname" disabled style="width: 250px"></el-input>
                    </el-form-item>
                    <el-form-item label="检查部门:">
                      <el-input v-model="formData.founderDeptname" disabled style="width: 250px"></el-input>
                    </el-form-item>
                    <el-form-item label="检查人员:">
                      <el-input v-model="formData.founderName" disabled style="width: 250px"></el-input>
                    </el-form-item>
                    <el-form-item label="被检查对象:">
                      <el-input v-model="formData.objname" disabled style="width: 250px"></el-input>
                    </el-form-item>
                    <el-form-item label="所属单位:">
                      <el-input v-model="formData.becheckedOrgname" disabled style="width: 250px"></el-input>
                    </el-form-item>
                    <el-form-item label="所属场所:" v-if="formData.siteName">
                      <el-input v-model="formData.siteName" disabled style="width: 250px"></el-input>
                    </el-form-item>
                    <el-form-item label="所属部位:" v-if='formData.partName'>
                      <el-input v-model="formData.partName" disabled style="width: 250px"></el-input>
                    </el-form-item>
                    <el-form-item label="检查类型:">
                      <el-select v-model="formData.sourcetype" disabled style="width: 250px">
                        <el-option v-for="item in D_BZ_YHLX" :key="item.value" :label="item.label"
                          :value="item.value"></el-option>
                      </el-select>
                    </el-form-item>

                    <el-form-item label="隐患级别:" prop="pitfallLevel">
                      <el-select v-model="formData.pitfallLevel" disabled style="width: 250px">
                        <el-option v-for="item in D_DBZ_YHDJ" :key="item.value" :label="item.label"
                          :value="item.value"></el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item v-if="isAudit ? isSelfFix == '1' : true" label="隐患类别:" prop="pitfallType">
                      <MOSTY.DictTree :zdbh="'D_TB_SBYHLB'" :disabled='isyhlb' v-model="formData.pitfallType"
                        :placeholder='"请选择隐患类别"' style="width: 250px;" />
                    </el-form-item>
                    <el-form-item label="隐患描述:">
                      <el-input v-model="formData.pitfallDescribe" disabled type="textarea" :rows="3" show-word-limit
                        style="width: 827px" />
                    </el-form-item>

                  </div>
                </el-collapse-item>
                <div v-if="(isAudit && (rwlx == 55 || rwlx == 70 || rwlx == 71 || rwlx == 72)) || props.type == '01'"
                  style="color:#000;display: flex;align-items: center;" class="mt10 mb10 p10">
                  <span>是否能自行整改：</span>
                  <el-radio-group v-model="isSelfFix" :disabled="isAqbm && isSgs">
                    <el-radio label="1">是</el-radio>
                    <el-radio label="2" :disabled="formData.state == '19'">否</el-radio>
                  </el-radio-group>
                </div>
                <template v-if="isSelfFix == '1'">
                  <el-collapse-item v-if="isAudit ? isSelfFix == '1' : true" title="整改措施(方案)信息" name="2">
                    <div class="searchBox">
                      <div class="titl">隐患分析</div>
                      <el-form-item label="原因分析:" prop="reformReasonanalysis">
                        <el-input v-model="formData.reformReasonanalysis" type="textarea" :rows="3" show-word-limit
                          maxlength="1000" placeholder="原因分析请不要超过1000个汉字" style="width: 827px" />
                      </el-form-item>
                      <div class="titl">制定方案</div>
                      <el-form-item label="整改责任部门:" prop="sendDeptname">
                        <el-input v-model="formData.sendDeptname" readonly :disabled="!isAqbm" style="width: 250px">
                          <template v-if="isAqbm" #append>
                            <el-button type="primary" @click="chooseDept">选择</el-button>
                          </template>
                        </el-input>
                      </el-form-item>
                      <el-form-item label="整改责任人:" prop="dutyUsername">
                        <el-input v-model="formData.dutyUsername" clearable readonly @click="ChooesDdld()"
                          style="width: 250px" />
                      </el-form-item>

                      <el-form-item label="整改期限:" prop="reformOvertime">
                        <el-date-picker v-model="formData.reformOvertime" :disabled="IsDisabled" type="date"
                          format="YYYY-MM-DD" clearable value-format="YYYY-MM-DD" style="width: 250px" />
                      </el-form-item>
                      <el-form-item label="投入预算：" prop="reformBudgetamount">
                        <el-input v-model.number="formData.reformBudgetamount" type="number" maxlength="12"
                          style="width: 250px">
                          <template #append>元</template>
                        </el-input>
                      </el-form-item>
                      <el-form-item label="整改措施:" prop="reformMeasure">
                        <el-input v-model="formData.reformMeasure" type="textarea" :disabled="IsDisabled" :rows="3"
                          show-word-limit style="width: 827px" />
                      </el-form-item>
                      <el-form-item label="临时控制措施:" prop="existingcontrols">
                        <el-input v-model="formData.existingcontrols" type="textarea" :rows="3" show-word-limit
                          maxlength="1000" placeholder="临时控制措施请不要超过1000个汉字" style="width: 827px" />
                      </el-form-item>

                    </div>
                  </el-collapse-item>
                </template>


              </el-collapse>
            </el-form>
          </div>
          <div class="pr15 pb15 pl40 ww20 hh100 scrollbar mystyle">
            <el-timeline>
              <el-timeline-item v-for="(activity, index) in data.zgjdList" :key="index" type="primary" placement="top"
                :color="activity.color" :timestamp="activity.time">
                {{ activity.content }}
              </el-timeline-item>
            </el-timeline>
          </div>

        </div>
      </template>
      <template #footer>

        <el-button type="primary" :loading="loading" @click="submitEvent(ruleFormRef)">
          <el-icon>
            <DocumentChecked />
          </el-icon>
          <span>{{ isBatch ? '批量保存' : '保存' }}</span>
        </el-button>
        <el-button @click="CloseEvent" type="primary">
          <el-icon>
            <DocumentDelete />
          </el-icon>
          <span>关闭</span>
        </el-button>
      </template>
    </MOSTY.FromPage>

    <ChooseUser v-model="chooseUserVisible" :Single="singleShow" :deptId="deptId" :leaderid="leaderid"
      @choosedUsers="getSonValue">
    </ChooseUser>
    <Choosebm :showDdld="showDept" :deptId="bmDeptId" :formInfo="{ zzid: formData.sendDeptid }" @closezzjg="closezzjg"
      @listdata="bmChange" :zzlx="bmZzlx" />
  </div>
</template>

<script setup>
import * as MOSTY from "@/components/MyComponents/index";
import { reactive, ref, watchEffect, getCurrentInstance, onMounted, watch } from "vue";
import ChooseUser from "@/components/MyComponents/ChooseUser/Leader.vue";
import { getApi, postApi } from "@/api/tobAcco_api.js";
import { ElMessage } from "element-plus";
import { filterqx } from "@/utils/auth.js";
import { getItem } from "@/utils/storage"
import Choosebm from "@/components/MyComponents/ChooseDept/index.vue";
import { getImgUrl, getErrMsg, czrw } from '@/utils/tools.js'
import { string } from "html-docx-js/dist/html-docx";

const { proxy } = getCurrentInstance();
const { D_BZ_YHLX, D_DBZ_YHDJ } = proxy.$dict("D_BZ_YHLX", "D_DBZ_YHDJ");
const chooseUserVisible = ref(false); //选择领导弹窗
const singleShow = ref(true); //单选多选
const leaderid = ref("");
const deptId = ref(null)
const zzlx = ref(null);
const bmZzlx = ref(null);
const activeNames = ["1", "2"];
const loading = ref(false);
const isSelect = ref(false); //是否是查看
const formData = ref({})
const IsDisabled = ref(false)
/** 是否展示部门TC */
const showDept = ref(false)
const bmDeptId = ref(getItem('deptId').ssdwid)
const isShowTimeLine = ref(false); //是否显示时间线
/** 是否安全部门 */
const isAqbm = ref(filterqx('isaqbm') == '1')
/**省公司 */
const isSgs = ref(filterqx('isSgs') == '1')
// 添加批量相关数据
const isBatch = ref(false); // 是否是批量模式
const batchData = ref([]); // 批量数据
const props = defineProps({
  saveBtnShow: {
    type: Boolean,
    default: true
  },
  Rowobj: {
    type: Object,
    default: {}
  },
  type: {
    type: String,
    default: '01',
  }
});
const ruleFormRef = ref();
const emit = defineEmits("changePage");
//规则校验
const rules = reactive({
  pitfallLevel: [{ required: true, message: "请选择隐患级别", trigger: "blur" }],
  pitfallType: [{ required: true, message: "请选择隐患类别", trigger: "blur" }],
  reformOvertime: [{ trigger: "blur", required: true, message: "请选择整改期限" }],
  dutyUsername: [{ trigger: "blur", required: true, message: "整改责任人不能为空" }],
  sendDeptname: [{ trigger: "blur", required: true, message: "整改责任部门不能为空" }],
  reformMeasure: [{ trigger: "blur", required: true, message: "整改措施不能为空" }],
  reformReasonanalysis: [{ trigger: "blur", required: true, message: "原因分析不能为空" }],
  reformBudgetamount: [{ trigger: "blur", required: true, message: "投入预算不能为空" }],
  existingcontrols: [{ trigger: "blur", required: true, message: "临时控制措施不能为空" }]
});
const isyhlb = ref(false)
const data = reactive({
  extendattr: {},
  config: {
    title: "",
    saveBtnShow: true
  },
  zgjdList: [] //整改进度数据
});


/** 是否是审核用 */
const isAudit = ref(false)
/**  是否能自行整改 1是 2否 审核用- */
const isSelfFix = ref('1')
/**任务类型 目前70 72 */
const rwlx = ref('')
/**任务id */
const rwid = ref('')
// watchEffect(() => {

// });
// 初始化
onMounted(() => {
  // 检查是否是批量模式
  if (props.Rowobj?.isBatch && props.Rowobj?.batchData) {
    isBatch.value = true;
    batchData.value = props.Rowobj.batchData;

    // 批量模式下，使用第一条数据初始化表单
    if (batchData.value.length > 0) {
      formData.value = { ...batchData.value };
      formData.value.reformOvertime = formData.value.planOvertime;
      formData.value.reformMeasure = formData.value.verifyDescribe;
      formData.value.founderOrgname = formData.value.founderOrgname ? formData.value.founderOrgname : '贵州省烟草专卖局（公司）';
      deptId.value = formData.value.belongDeptid;
      formData.value.sendDeptname = formData.value.belongDeptname;
      formData.value.sendDeptid = formData.value.belongDeptid;
      IsDisabled.value = false;
    }
  } else {
    isAudit.value = props.Rowobj.isAudit
    rwlx.value = props.Rowobj.rwlx // 70 72
    rwid.value = props.Rowobj.rwid
    if (props.Rowobj) {
      // 综合检查、随手拍
      formData.value = props.Rowobj;
      isyhlb.value = formData.value.pitfallType ? true : false
      formData.value.reformOvertime = formData.value.planOvertime
      formData.value.reformMeasure = formData.value.verifyDescribe
      formData.value.founderOrgname = formData.value.founderOrgname ? formData.value.founderOrgname : '贵州省烟草专卖局（公司）'
      if (props.Rowobj.refHzid) {
        IsDisabled.value = true
        getzgcs(props.Rowobj.refHzid)
        getzgdept(props.Rowobj.id)

      } else {
        deptId.value = props.Rowobj.belongDeptid
        formData.value.sendDeptname = props.Rowobj.belongDeptname
        formData.value.sendDeptid = props.Rowobj.belongDeptid
        IsDisabled.value = false
      }

      isSelect.value = true;
      isShowTimeLine.value = true;
    }
  }
  _getZgjdData(props.Rowobj.id);

});
//获取整改措施
function getzgcs(hzId) {
  getApi({ hzId }, '/mosty-jcgl/overallCheckPitfallHz/getHzInfo').then(res => {
    formData.value.reformReasonanalysis = res.reformReasonanalysis
    formData.value.reformOvertime = res.reformOvertime
    // formData.value.sendDeptname = res.sendDeptname
    // formData.value.sendDeptid = res.sendDeptid
    // deptId.value = res.sendDeptid
    formData.value.reformMeasure = res.reformMeasure
    formData.value.reformBudgetamount = res.reformBudgetamount;
    // if (res.reformUploadfile) {
    //       getApi({}, `/mosty-base/minio/file/download/${item.pics}`).then(
    //     (res) => {
    //       item.picsUrl = res.url
    //     }
    //   );
    // }
  })
}
//获取整改部门
function getzgdept(id) {
  getApi({}, '/mosty-jcgl/overallCheckPitfallHz/getDutyDept?yhid=' + id).then(res => {
    if (res) {
      formData.value.sendDeptname = res.deptname
      formData.value.sendDeptid = res.deptid
      deptId.value = res.deptid
    }
  })
}
function chooseDept() {
  showDept.value = true;
}
function ChooesDdld(val) {
  zzlx.value = val;
  leaderid.value = "";

  singleShow.value = true;
  chooseUserVisible.value = true;
}
//关闭弹窗
const closezzjg = (val) => {
  showDept.value = val;
};
const bmChange = (val) => {
  //sendDeptname
  formData.value.sendDeptname = val.orgName
  formData.value.sendDeptid = val.id
  deptId.value = val.id
  // 清空责任人
  formData.value.dutyUsername = ''
  formData.value.dutyUserid = ''
}
const getSonValue = (value) => {
  formData.value.dutyUsername = value[0].userName;
  formData.value.dutyUserid = value[0].id;

};
// 保存
const submitEvent = async (formEl) => {
  if (!formEl) {
    ElMessage.warning('请输入必填项！！！')
  }
  await formEl.validate((valid, fields) => {
    if (valid) {
      loading.value = true;
      // 批量整改逻辑
      if (isBatch.value) {
        // 为每条隐患生成完整的整改数据
        const batchSubmitData = batchData.value.map(row => ({
          pitfallDescribe: row.pitfallDescribe, // 使用每条隐患自己的描述
          pitfallLevel: row.pitfallLevel, // 使用每条隐患自己的级别
          pitfallType: row.pitfallType, // 使用每条隐患自己的类型
          yhid: row.id, // 每条隐患自己的ID
          budgetAmount: formData.value.reformBudgetamount,// 使用公共的预算金额
          dutyUserid: formData.value.dutyUserid,// 使用公共的责任人ID
          dutyUsername: formData.value.dutyUsername,// 使用公共的责任人
          existingControls: formData.value.existingcontrols,// 使用公共的临时控制措施
          planOvertime: formData.value.reformOvertime,// 使用公共的计划完成时间
          reason: formData.value.reformReasonanalysis,// 使用公共的原因分析
          reformMeasure: formData.value.reformMeasure,// 使用公共的整改措施
          dutyDeptid: formData.value.sendDeptid,// 使用公共的发送部门ID
          dutyDeptname: formData.value.sendDeptname,// 使用公共的发送部门名称
        }));
        postApi(batchSubmitData, "/mosty-jcgl/process/batchAddScheme")
          .then((res) => {
            loading.value = false;
            ElMessage.success(`批量处理成功，共处理 ${batchData.value.length} 条隐患`);
            emit("changePage");
          })
          .catch((err) => {
            loading.value = false;
            ElMessage.error("批量处理失败");
          });
      } else {
        let data = {
          budgetAmount: formData.value.reformBudgetamount,
          dutyUserid: formData.value.dutyUserid,
          dutyUsername: formData.value.dutyUsername,
          existingControls: formData.value.existingcontrols,
          pitfallDescribe: formData.value.pitfallDescribe,
          pitfallLevel: formData.value.pitfallLevel,
          pitfallType: formData.value.pitfallType,
          planOvertime: formData.value.reformOvertime,
          reason: formData.value.reformReasonanalysis,
          reformMeasure: formData.value.reformMeasure,
          dutyDeptid: formData.value.sendDeptid,
          dutyDeptname: formData.value.sendDeptname,
          yhid: formData.value.id,
        }
        // 是否能自行整改
        if (isAudit) data.state = isSelfFix.value
        if (!props.Rowobj.refHzid) {
          //	待处理隐患-制定整改方案
          postApi(data, "/mosty-jcgl/process/addScheme")
            .then((res) => {
              loading.value = false;

              ElMessage.success("处理成功");
              if (rwid.value) {
                czrw(rwid.value).then(res => {
                  emit("changePage", false);
                })
              } else {
                emit("changePage", false);
              }
            })
            .catch((err) => {
              loading.value = false;
            });
        } else {
          //	待处理隐患-指定整改人
          postApi(data, "/mosty-jcgl/overallCheckPitfallHz/addDutyUser")
            .then((res) => {
              loading.value = false;
              ElMessage.success("处理成功");
              if (rwid.value) {
                czrw(rwid.value).then(res => {
                  emit("changePage", false);
                })
              } else {
                emit("changePage", false);
              }
            })
            .catch((err) => {
              loading.value = false;
            });
        }
      }

    } else {
      ElMessage.warning(getErrMsg(fields) || "请检查表单!");
    }
  })
}
const handleChange = (val) => {
}
function CloseEvent() {
  proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
    .then(() => {
      emit("changePage", false);
    })
    .catch(() => {
      // catch error
    })


}

//获取进度数据
const _getZgjdData = (id) => {
  getApi({ id }, "/mosty-jcgl/yhb/getYhTimer").then((res) => {
    if (res) {
      for (let i = 0; i < res.length; i++) {
        switch (res[i].state) {
          case "01":
            res[i].color = "blue";
            break;
          case "02":
            res[i].color = "orange";
            break;
          case "03":
            res[i].color = "red";
            break;
          case "04":
            res[i].color = "green";
            break;
        }
      }
      data.zgjdList = res;
    }
  });
};


</script>

<style lang="scss" scoped>
.mystyle {
  margin-top: 25px;
  margin-right: 100px;
}
.titl {
  text-align: left;
  padding-left: 5px;
  width: 100%;
  border-bottom: 1px dashed #44a48c;
  font-size: 16px;
  color: #44a48c;
  margin: 20px 0px 10px 0px;
}

.box_cont {
  display: flex;
  background: #fff;
  margin: 20px 20px 20px auto;
  overflow-y: scroll;
}

.box-left {
  width: 63%;
}

.pic_left {
  width: 110px;
  height: 130px;
  display: flex;
  align-content: center;
  justify-content: center;
  overflow: hidden;
  border: 1px solid rgba(0, 0, 0, 0.1);
  margin-left: 15px;
}

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



::-webkit-scrollbar {
  width: 0 !important;
  height: 0;
}

.searchBox {
  width: 1000px;
  margin: 15px auto;
  color: #333;
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}

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

::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-radio__label {
//   display: none;
// }

::v-deep .el-collapse-item__header {
  color: #fff !important;
  background-color: var(--el-color-primary) !important;
}
</style>
