<template>
  <div>
    <MOSTY.PageTree pageTitle="聘用安全人员" :searchType="'03'" @getDeptId="getdeptData">
      <template #serach>
        <el-divider />
        <div class="box">
          <div class="flxbox">
            <div>
              <el-input v-model="listQuery.userName" clearable placeholder="请输入人员姓名" style='width: 250px;'
                class="mr20" />
            </div>
            <el-input v-model="listQuery.orgName" clearable placeholder="请输入单位名称姓名" style='width: 250px;'
              class="mr20" />
          </div>
          <div class="butBox">
            <el-button icon="search" type="primary" @click="onSearch">查询</el-button>
            <el-button icon="Refresh" @click="reset">重置</el-button>
          </div>
        </div>
        <el-divider />
        <div class="btnBox">
          <!-- <el-button type="primary" @click="addUserHander">
            <el-icon>
              <CirclePlus />
            </el-icon>
            <span>新增</span>
          </el-button> -->
          <!-- <el-button type="primary" :loading="loadingshow" @click="onloadExcel">
						<el-icon>
							<Download />
						</el-icon>
						<span>导出</span>
					</el-button> -->
        </div>
      </template>
      <template #table>
        <section class="eltab9">
          <MOSTY.Table :table-columns="tableColumn" :tableData="tableData" :tableloading="tableloading"
            :isSelect="false" :isSort="false" @SortChange="SortChange" style="width: 100%;">
            <!-- <template #type="{ row }">
							<dict-tag :options="D_BZ_RCLX" v-for="item in row.type" :key="item" :value="item" />
						</template> -->
            <template #staffType="{ row }">
              <span>{{ row.staffType === '0' ? "专职" : "兼职" }}</span>
            </template>
            <template #reviewResult="{ row }">
              <span>{{ row.reviewResult === '1' ? "审核通过" : row.reviewResult === '2' ? "审核未通过-" + row.reviewNote : "审核中"
              }}</span>
            </template>
            <!-- 操作 -->
            <template #actions="{ row }">
              <span v-if="row.reviewResult === '1'" class="operdel" size="small"
                @click="downloadAppointment(row)"><el-icon>
                  <Download />
                </el-icon>聘任书下载</span>
              <span class="operedit" @click="toExamine(row)"
                v-if="row.reviewStatus === '1' && USERID === row.reviewUserId">
                <!-- <span v-if="USERID === row.reviewUserId" class="operedit" @click="toExamine(row)"> -->
                <el-icon>
                  <EditPen />
                </el-icon>审核
              </span>
              <span class="operedit" @click="clickEdit(row)">
                <el-icon>
                  <EditPen />
                </el-icon>编辑
              </span>
              <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="确定要删除?"
                @confirm="deldete(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="pageConfiger" @changeNo="handleCurrentChange" @changeSize="handleSizeChange">
          </MOSTY.Pages>
        </div>
      </template>
    </MOSTY.PageTree>
    <el-dialog :title="'安全人员审核'" width="600px" v-model="isShowExamine" :before-close="closed">
      <el-form :model="examineForm" :rules="rules" ref="examineFormRef" label-width="100px">
        <el-form-item label="审核结果" prop="reviewResult">
          <el-radio-group v-model="examineForm.reviewResult">
            <el-radio :label="'1'">通过</el-radio>
            <el-radio :label="'2'">不通过</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="examineForm.reviewResult === '2'" label="不通过理由" prop="reviewNote">
          <el-input v-model="examineForm.reviewNote" type="textarea" :rows="4" placeholder="请输入不通过的理由"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="flex just-between">
          <span class="dialog-footer">
            <el-button type="primary" @click="handleSave(examineFormRef)">
              <el-icon>
                <DocumentChecked />
              </el-icon>
              <span>确定</span>
            </el-button>
            <el-button @click="closed" type="primary">
              <el-icon>
                <DocumentDelete />
              </el-icon>
              <span>关闭</span>
            </el-button>
          </span>
        </div>
      </template>
    </el-dialog>
    <AddEdit ref="addEditRef" v-if="dialogVisible" @ok="addEditOk" @close="dialogVisible = false"></AddEdit>
  </div>
</template>

<script setup>
// import ChooseUser from "@/components/MyComponents/ChooseUser/Leader.vue";
import * as MOSTY from "@/components/MyComponents/index";
import { getApi, postApi, deleteApi } from "@/api/tobAcco_api.js";
import AddEdit from "@/views/dutyBook/jgryandzz/anQuanRydj/addEdit.vue"
import { ElMessage } from "element-plus";
import {
  ref,
  onMounted,
  getCurrentInstance,
  reactive,
  nextTick
} from "vue";
const { proxy } = getCurrentInstance();
// const { D_BZ_RCLX, D_BZ_ZCXFGCSJB, D_BZ_ZCAQGCSJB, D_BZ_SF } = proxy.$dict("D_BZ_RCLX", "D_BZ_ZCXFGCSJB", "D_BZ_ZCAQGCSJB", "D_BZ_SF")
const loadingshow = ref(false);
const USERID = window.localStorage.getItem("USERID")
const tableColumn = ref([
  { title: "聘用人员姓名", prop: "userName" },
  // { title: "评聘开始时间", prop: "startDate" },
  // { title: "评聘结束时间", prop: "endDate" },
  { title: "聘用人员单位", prop: "orgName" },
  { title: "聘用人员部门", prop: "deptName" },
  { title: "安全员类型", prop: "staffType", slot: true, },
  { title: "审核状态", prop: "reviewResult", slot: true, },
  // { title: "评聘文件", prop: "assessEmployFile", },
  // { title: "年度履职报告", prop: "deputyActivityFile", },
  // { title: "年度考核结果", prop: "examineResultFile", },
  // { title: "其他资料", prop: "otherFile", },
  { title: "备注", prop: "bz", },
  { title: "操作", prop: "actions", slot: true }
])
const pageConfiger = reactive({
  pageSize: 20,
  pageCurrent: 1,
  total: 0
})
const dialogVisible = ref(false)
/** 新增编辑ref */
const addEditRef = ref()
const tableLoading = ref(false)
const deptId = ref(null);
const leaderid = ref("");
const chooseUserVisible = ref(false)
const addLoading = ref(false)
const memberList = ref([]);//默认选中的人员

const SortChange = () => { }

//查询参数
const total = ref(0);
// 类型区分 1 聘用安全人员 2 评聘安全人员
const listQuery = ref({
  pageCurrent: 1,
  pageSize: 20,
  assessType: '1'
});
const pageData = reactive({
  fromObj: {
    userId: "",
    //人才类型
    list: [{
      type: "",
      level: "",
      files: ""
    }],
  },

})
// 数据相关
const tableData = ref([]);
// tableloading
const tableloading = ref(false);

onMounted(() => {
});
//选择右侧部门
function getdeptData(val) {
  listQuery.value.orgId = val.id;
  listQuery.value.pageCurrent = 1;
  pageConfiger.pageCurrent = 1;
  getListData()
}


/**
 * 新增或者编辑成功
 */
const addEditOk = () => {
  dialogVisible.value = false
  getListData()
}

// 获取数据的方法
const getListData = async () => {
  tableLoading.value = true
  postApi(listQuery.value, "/mosty-jcgl/assessEmployStaff/getAssessEmployStaff").then(res => {
    if (res) {
      total.value = res.total;
      tableData.value = res.records;
      pageConfiger.total = res.total;
    }
  }).finally(() => {
    tableLoading.value = false
  })
};
//
/**查询 */
const onSearch = (obj) => {
  listQuery.value.pageCurrent = 1;
  pageConfiger.pageCurrent = 1;
  getListData();
};
const reset = (obj) => {
  listQuery.value.pageCurrent = 1;
  pageConfiger.pageCurrent = 1;
  listQuery.value.userName = '';
  listQuery.value.orgName = '';
  listQuery.value.level = null;
  getListData();
};
/**分页数 */
const handleSizeChange = (currentSize) => {
  listQuery.value.pageSize = currentSize;
  pageConfiger.pageSize = currentSize;
  getListData();
};

const handleCurrentChange = (currentPage) => {
  listQuery.value.pageCurrent = currentPage;
  pageConfiger.pageCurrent = currentPage;
  getListData();
};
const addUserHander = (row) => {
  dialogVisible.value = true;
  nextTick(() => {
    addEditRef.value.init()
  })
};


/**
 * 编辑
 * @param row 行
 */
const clickEdit = (row) => {
  dialogVisible.value = true;
  nextTick(() => {
    addEditRef.value.init(row)
  })

}
// 审核弹窗
const isShowExamine = ref(false)
// 审核表单ref
const examineFormRef = ref()
// 审核表单数据
const examineForm = reactive({
  id: '',
  reviewResult: 1, // 1通过 0不通过
  reviewNote: null
})
// 表单验证规则
const rules = {
  reviewResult: [
    { required: true, message: '请选择审核结果', trigger: 'change' }
  ],
  reviewNote: [
    {
      required: true,
      message: '不通过理由不能为空',
      trigger: 'blur',
      validator: (rule, value, callback) => {
        if (examineForm.reviewResult === 0 && !value) {
          callback(new Error('不通过理由不能为空'))
        } else {
          callback()
        }
      }
    }
  ]
}
// 聘任书下载
const downloadAppointment = (row) => {
  if (row.id) {
    getApi({}, `/mosty-jcgl/assessEmployStaff/download/${row.id}`)
      .then((res) => {
        if (res) {
          const base64String = res;
          const cleanBase64 = base64String.replace(/^data:.+;base64,/, '');
          try {
            const byteCharacters = atob(cleanBase64);
            const byteNumbers = new Array(byteCharacters.length);
            for (let i = 0; i < byteCharacters.length; i++) {
              byteNumbers[i] = byteCharacters.charCodeAt(i);
            }
            const byteArray = new Uint8Array(byteNumbers);
            const blob = new Blob([byteArray], {
              type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
            });
            const fileName = row.userName + `聘任书.docx`;
            downloadFile(blob, fileName)
            console.log('文件下载成功:', fileName);
          } catch (error) {
            console.error('Base64解码失败:', error);
            ElMessage.error('文件处理失败');
          }
        }
      });
  }
}
function downloadFile(blob, fileName) {
  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');

  link.href = url;
  link.download = fileName;
  link.style.display = 'none';

  document.body.appendChild(link);
  link.click();

  // 清理
  setTimeout(() => {
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
  }, 100);
}
// 安全员审核
const toExamine = (row) => {
  isShowExamine.value = true
  examineForm.id = row.id
}
const handleSave = async (examineFormRef) => {
  if (!examineFormRef) return;
  await examineFormRef.validate((valid) => {
    if (valid) {
      postApi(examineForm, "/mosty-jcgl/assessEmployStaff/reviewAssessEmploy")
        .then((res) => {
          getListData();
          ElMessage.success("审核完成");
          isShowExamine.value = false
        }).finally(() => {
          examineForm = {
            id: '',
            reviewResult: 1,
            reviewNote: null
          }
        })
    } else {
      ElMessage.error("请输入必填项!");
    }
  });
};
const closed = () => {
  if (!examineFormRef.value) return
  proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
    .then(() => {
      isShowExamine.value = false
    })
    .catch(() => {
      // catch error
    })
};
const deldete = (row) => {
  postApi([row.id], `/mosty-jcgl/assessEmployStaff/delAssessEmployStaff`).then(res => {
    proxy.$message.success("删除成功")
    getListData()
  })
};

// //导出Excel
// function onloadExcel() {
// 	loadingshow.value = true
// 	let title = {
// 		orgName: "所属单位",
// 		deptName: "所属部门",
// 		userName: "人员姓名",
// 		type: "人才类型",
// 	};

// 	getApi(listQuery.value, "/mosty-jcgl/talents/exportData").then(async (res) => {
// 		if (res) {
// 			let data = res;
// 			if (data) {
// 				for (let i = 0; i < data.length; i++) {

// 					data[i].type = data[i].type.split(",").map(el => {
// 						return proxy.$getDictVal(el, D_BZ_RCLX);
// 					}).toString()

// 				}
// 				let tablename = "人才库管理列表.xlsx";
// 				exportXlsx(title, data, '人才库管理列表', tablename);
// 			}
// 		}
// 	}).finally(() => {
// 		loadingshow.value = false
// 	});
// }

</script>

<style lang="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: center;
  text-align: center;
}

.treeBox {
  overflow: auto;
}


::v-deep .el-form {
  flex-wrap: wrap;
  display: flex;
  flex-direction: column;
}

// ::v-deep .el-input-group__append {
//   background: var(--el-color-primary);
//   color: #fff;
// }

// ::v-deep .el-form-item__content {
//   display: flex;
//   justify-content: space-between;
// }

.btnBox {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-bottom: 12px;
}

.box {
  display: flex;
  justify-content: space-between;
  margin-bottom: 22px;
  // flex-wrap: wrap;

  .flxbox {
    display: flex;
    flex-wrap: wrap;
  }

  .item {
    display: flex;
    margin-right: 20px;
    margin-bottom: 10px;
  }

  .label {
    margin: auto;
    margin-right: 5px;
    text-wrap: nowrap;
  }
}

.butBox {
  flex: 1;
  width: 200px;
  display: flex;
  justify-content: flex-end;
}
</style>