<template>
  <MOSTY.PageTree :pageTitle="'危险作业管理列表'" :searchType="'01'" @getDeptId="getdeptData">
    <template #serach>
      <el-divider />
      <MOSTY.Search :searchArr="searchArr" @submit="onSearch" />
      <el-divider />
      <section class="button">
        <el-button @click="addInfo"><el-icon size="small">
            <Plus />
          </el-icon>申请</el-button>
      </section>
    </template>
    <template #table>
      <section class="eltab9">
        <MOSTY.Table :tableData="tableData" :table-columns="tableColumn" :tableloading="tableloading"
          :tableConfiger="tableConfiger" actionsW="300">
          <template #zylb="{ row }">
            <dict-tag v-if="row.zylb" :options="D_BZ_WXZYLXNEW" :value="row.zylb" :tag="false" />
            <span v-else>无</span>
          </template>
          <template #state="{ row }">
            <dict-tag v-if="row.state" :options="spdata" :value="row.state" :tag="false" />
            <span v-else>无</span>
          </template>
          <!--操作-->
          <template #actions="scope">
            <span class="operesee" @click="handleSee(scope.row, 'see')"><el-icon>
                <Compass />
              </el-icon>查看</span>
            <span v-if="scope.row.state < 2 || scope.row.state == null" class="operedit"
              @click="handleEdit(scope.row, 'edit')">
              <el-icon>
                <EditPen />
              </el-icon>
              编辑
            </span>
            <el-popconfirm v-if="scope.row.state < 2 || scope.row.state == null" confirm-button-text="是"
              cancel-button-text="否" icon-color="red" title="确定要提交审核?" @confirm="audit(scope.row)">
              <template #reference>
                <span class="operesee" size="small">
                  <el-icon>
                    <EditPen />
                  </el-icon>
                  提交审核
                </span>
              </template>
            </el-popconfirm>
            <el-popconfirm v-if="scope.row.state === '05'" confirm-button-text="是" cancel-button-text="否"
              icon-color="red" title="确定作业完成进行归档?" @confirm="sumbuitAudit(scope.row)">
              <template #reference>
                <span class="operesee" size="small">
                  <el-icon>
                    <EditPen />
                  </el-icon>
                  归档
                </span>
              </template>
            </el-popconfirm>
            <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="确定要删除?"
              @confirm="handleDel(scope.row)">
              <template #reference>
                <span class="operdel" size="small">
                  <el-icon>
                    <Delete />
                  </el-icon>
                  删除
                </span>
              </template>
            </el-popconfirm>
          </template>
        </MOSTY.Table>
      </section>
      <div class="fenye">
        <MOSTY.Pages :pageConfiger="listQuery" @changeNo="handleCurrentChange" @changeSize="handleSizeChange" />
      </div>
    </template>
  </MOSTY.PageTree>
  <!-- 新增 -->
  <div v-if="comprehensiveShow" class="dialog-box">
    <Wxzyxq :saveBtnShow="saveBtnShow" :editObj="editObj.editObj" @close="close" :zdlist='{ D_BZ_WXZYLXNEW }'
      :title="editObj.title" :rwid="rwid" :p1="p1" :examineshow="examineshow" />
  </div>
</template>
<script setup>
// 引入
import { reactive, onMounted, ref, getCurrentInstance } from "vue";
import Wxzyxq from "@/views/yxkzgl/wxzyxq.vue";
import { getApi, postApi } from "@/api/tobAcco_api.js";
import * as MOSTY from "@/components/MyComponents/index";
import { useRoute } from "vue-router";
import { ElMessage } from "element-plus"
const { proxy } = getCurrentInstance();
const { D_BZ_WXZYLXNEW } = proxy.$dict("D_BZ_WXZYLXNEW");
const searchArr = reactive([
  {
    showType: "input",
    prop: "sitename",
    placeholder: "请输入场所名称进行查询"
  }
])
const tableConfiger = ref()
const tableColumn = reactive([
  {
    title: "单位名称",
    prop: "askunitname",
  },
  {
    title: "申请部门",
    prop: "askdeptname",
  },
  {
    title: "作业类型",
    prop: "zylb",
    slot: true
  },
  {
    title: "作业地点",
    prop: "jobplace",
  },
  {
    title: "作业开始时间",
    prop: "jobstarttime",
  },
  {
    title: "作业结束时间",
    prop: "jobendtime",
  },
  {
    title: "场所名称",
    prop: "sitename",
  },
  {
    title: "现场监护人",
    prop: "sitemanagername",
  },
  {
    title: "状态",
    prop: "state",
    slot: true
  },
  {
    title: "操作",
    prop: "actions",
    slot: true
  }
])
// 数据
const comprehensiveShow = ref(false);
/** 任务列表 -跳转过来的p1 */
const p1 = ref()
/** 状态 */
const spdata = reactive([
  { value: "00", label: "新增" },
  { value: "01", label: "提交审核" },
  { value: "02", label: "相关方归口部门负责人上传资料" },
  { value: "03", label: "安全部门审核资料" },
  { value: "04", label: "责任部门现场确认" },
  { value: "05", label: "作业过程中" },
  { value: "06", label: "责任部门上传资料归档" },
  { value: "07", label: "作业部门安全员审核" },
  { value: "08", label: "作业部门负责人审核" },
  { value: "09", label: "单位主要负责人审核" },
  { value: "10", label: "业务部门归口安全员审核（省/市级）" },
  { value: "11", label: "业务部门归口负责人审核（省/市级）" },
  { value: "12", label: "安全部门注册安全师审核" },
  { value: "13", label: "安全部门负责人审核" },
  { value: "14", label: "安全部门负责人审核（带授权书）" },
  { value: "15", label: "主要领导" },
  { value: "16", label: "归档" },
]);
//查询条件
const editObj = reactive({
  deptname: "",
  title: "",
  savebtn: true,
  seeimg: true,
  editObj: {},
  formData: {}
});
const tableData = ref([]);
// 分页
const listQuery = reactive({
  pageCurrent: 1,
  pageSize: 20,
  total: 0,
  orgcode: ""
});
//获取部门数据
const getdeptData = (val) => {
  listQuery.orgcode = val.id;
  listQuery.pageCurrent = 1;
  getListData();
};
const tableloading = ref(false);
const saveBtnShow = ref(true);
const examineshow = ref(false);
const rwid = ref("");
const route = useRoute();
// 初始化
onMounted(() => {
  examinel();
});
function onSearch(obj) {
  listQuery.sitename = obj.sitename;
  listQuery.pageCurrent = 1;
  getListData()
}
// 获取表格数据
function getListData() {
  tableloading.value = true;
  const params = {
    ...listQuery,
    askdeptid: listQuery.orgcode,

  }
  delete params.orgcode;
  getApi(params, `/mosty-jcgl/dangerJob/getPageList`).then((res) => {
    if (res.records) {
      tableloading.value = false;
      tableData.value = res.records;
      listQuery.total = res.total;
    } else {
      tableData.value = [];
      tableloading.value = false;
    }
  }).finally(() => {
    tableloading.value = false;
  });
}
//弹窗关闭
const close = () => {
  comprehensiveShow.value = false;
  examineshow.value = false;
  getListData();
};

/** 清空之前不应该存在的内容 ,不然流程驳回时,会回显之前的数据*/
const clearVal = (res) => {
  // xgffile 危险作业资料
  if (res.xgffile) {
    if (['02'].includes(res.state) && res.zydx == '02') res.xgffile = ''
  }
  // 审核说明
  if (res.content) {
    if (['03', '04', '07'].includes(res.state)) res.content = ''
  }
  // 是否符合作业条件
  if (res.sffh) {
    if (['04'].includes(res.state)) res.sffh = ''
  }
  // 现场照片
  if (res.sceneImg) {
    if (['04'].includes(res.state)) res.sceneImg = ''
  }
  // 过程监护和监管内容
  if (res.processDesc) {
    if (['05'].includes(res.state)) res.processDesc = ''

  }
  // 过程监护和监管图片
  if (res.processImg) {
    if (['05'].includes(res.state)) res.processImg = ''
  }
  // 施工方案附件
  if (res.file) {
    if (['06'].includes(res.state)) res.file = ''
  }
  // 归口管理部门上传资料
  if (res.otherFile) {
    if (['06'].includes(res.state)) res.otherFile = ''
  }
}
//详情
const getmain = async (id, from) => {
  if (!id) return;

  const apiEndpoints = {
    getInfo: "/mosty-jcgl/dangerJob/getInfo", // 基本信息
    queryBuildpeopleByDangerjobid: "/mosty-jcgl/buildpeople/queryBuildpeopleByDangerjobid", // 人员
    getTimer: "/mosty-jcgl/dangerJob/getTimer" // 时间轴
  };

  try {
    // 并行执行多个 API 请求
    const [res, tbBuildpeopleList, timeLineArr] = await Promise.all([
      getApi({ id }, apiEndpoints.getInfo),
      getApi({ id }, apiEndpoints.queryBuildpeopleByDangerjobid),
      getApi({ id }, apiEndpoints.getTimer)
    ]);

    if (res) {
      if (from === 'examinel') clearVal(res)
      editObj.editObj = res;
      editObj.editObj.tbBuildpeopleList = Array.isArray(tbBuildpeopleList) ? tbBuildpeopleList : [];
      editObj.editObj.timeLineArr = Array.isArray(timeLineArr) ? timeLineArr : [];

      if (!examineshow.value) {
        const defaultOpinion = '暂无';
        editObj.editObj.deptpersonopinion = editObj.editObj.deptpersonopinion || defaultOpinion;
        editObj.editObj.fgldoption = editObj.editObj.fgldoption || defaultOpinion;
        editObj.editObj.branchedleadopinion = editObj.editObj.branchedleadopinion || defaultOpinion;
        editObj.editObj.manageroption = editObj.editObj.manageroption || defaultOpinion;
      }
    }
  } catch (error) {
    console.error('Error fetching data:', error);
  }
};
//新增
function addInfo() {
  editObj.editObj = null;
  comprehensiveShow.value = true;
  saveBtnShow.value = true;
  editObj.title = "危险作业申请";
}
//详情
function handleSee(row) {
  editObj.title = "危险作业详情";
  examineshow.value = false
  getmain(row.id);
  comprehensiveShow.value = true;
  saveBtnShow.value = false;
}
function handleEdit(row) {
  editObj.title = "危险作业编辑";
  examineshow.value = false
  getmain(row.id);
  comprehensiveShow.value = true;
  saveBtnShow.value = true;
}
const audit = (row) => {
  tableloading.value = true
  postApi({}, `/mosty-jcgl/dangerJob/submitNewOne/${row.id}`).then(() => {
    ElMessage.success("提交审核成功");
    getListData();
  }).finally(() => {
    tableloading.value = false
  })
}
const sumbuitAudit = (row) => {
  tableloading.value = true
  postApi({ id: row.id, state: '16' }, `/mosty-jcgl/dangerJob/archive`).then(() => {
    ElMessage.success("归档成功");
    getListData();
  }).finally(() => {
    tableloading.value = false
  })
}
const handleDel = (row) => {
  postApi({}, `/mosty-jcgl/dangerJob/del/${row.id}`).then(() => {
    ElMessage.success("删除成功");
    getListData();
  })
}
//分页
const handleSizeChange = (currentSize) => {
  listQuery.pageSize = currentSize;
  getListData();
};
const handleCurrentChange = (currentPage) => {
  listQuery.pageCurrent = currentPage;
  getListData();
};
const examinel = () => {
  // 跳转过来走这里
  if (route.query.id) {
    rwid.value = route.query.rwid;
    p1.value = route.query.p1
    saveBtnShow.value = false;
    examineshow.value = true;
    editObj.title = "危险作业审核";
    getmain(route.query.id, 'examinel');
    comprehensiveShow.value = true;
  }
};
</script>

<style lang="scss" scoped>
.button {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-bottom: 12px;
}
</style>