<template>
  <div class="bigBox">
    <div class="right">
      <!-- 头部 -->
      <MOSTY.Assort title="安全人员登记">
        <template #btn>
          <div class="btnBox">
            <el-button type="primary" @click="CloseEvent()">
              <el-icon>
                <Back />
              </el-icon>
              <span>返回</span>
            </el-button>
          </div>
        </template>
      </MOSTY.Assort>
    </div>
    <div class="searchBox" ref="searchBox">
      <el-form ref="ruleFormRef" :model="fromObj" :inline="true" :rules="rules"
        style="justify-content: start !important;">
        <div class="ld_box">
          <el-form-item label="负责人:" prop="executivename">
            <el-input v-model="fromObj.executivename" style="width: 250px" />
          </el-form-item>
          <el-button type="primary" @click="ChooesDdld('01')">选择</el-button>
        </div>
        <div class="ld_box">
          <el-form-item label="分管领导:" prop="leadershipname">
            <el-input v-model="fromObj.leadershipname" style="width: 250px" />
          </el-form-item>
          <el-button type="primary" @click="ChooesDdld('02')">选择</el-button>
        </div>
      </el-form>
      <!-- <div style="display: flex;align-items: center;height: 42px;width:786px;margin-top: 5px;white-space: nowrap;">
        <el-form-item label="兼职安全员认证文件">
        <span class="fj-label">兼职安全员认证文件:</span>
        <MOSTY.Upload v-if="isShowUpLoad" isAutoWidth :widthNumber="450" :limit="1" :nopicer="true" :isImg="false"
          :ShowfileList="false" v-model="fromObj.jzFiles" :showinput="true" @filehandleChange="filehandleChange">
        </MOSTY.Upload>
        <el-popconfirm v-if="fromObj.jzFiles && fromObj.jzFiles.length" confirm-button-text="是" cancel-button-text="否"
          icon-color="red" title="确定要删除?" @confirm="clearFile(row)">
          <template #reference>
            <span style="white-space: nowrap;" class="operdel"><el-icon>
                <Delete class="clear-icon" />
              </el-icon>清空附件</span>
          </template>
        </el-popconfirm>
        <el-button type="primary" plain @click="clearFile">清空附件</el-button>
        </el-form-item>
      </div> -->
      <div class="btnBox">
        <!--        v-if="fromObj.mtcsoltype != '0'"-->
        <el-button type="primary" @click="addShow">
          <el-icon>
            <CirclePlus />
          </el-icon>
          <span>新增</span>
        </el-button>
      </div>

    </div>
    <section class="eltabs3 mt10">
      <span id="btnBoxTetxt" v-if="fromObj.mtcsoltype == '0'">*按照国家局行业安全生产管理系统要求，专职安监部门所有专职安全管理人员均需登记</span>
      <MOSTY.Table :table-columns="tabColumns" :tableData="fromObj.ryList" :tableHeight="'100%'" :isSelect="false"
        :actionsW="'300'" style="width: 100%;" :isSort="true">
        <template #xb="{ row }">
          <dict-tag :options="D_BZ_XB" :value="row.xb" :tag="false" />
        </template>
        <template #aqrylx="{ row }">
          <dict-tag :options="D_TB_ZJZLX" :value="row.aqrylx" :tag="false" />
        </template>
        <template #actions="{ row }">
          <span v-if="row.enableTransfer" class="operesee" @click="updateTransfer(row)">
            <el-icon>
              <EditPen />
            </el-icon>调岗</span>
          <span class="operedit" @click="updateRows(row)">
            <el-icon>
              <EditPen />
            </el-icon>修改</span>
          <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="确定要删除?"
            @confirm="delRole(row)">
            <template #reference>
              <span class="operdel"><el-icon>
                  <Delete />
                </el-icon>删除</span>
            </template>
          </el-popconfirm>
          <span @click="showRows(row)" class="operesee">
            <el-icon>
              <Compass />
            </el-icon>查看</span>
        </template>
      </MOSTY.Table>

    </section>
    <el-dialog :title="'安全人员调岗'" width="600px" v-model="isShowTransfer" :before-close="closed">
      <el-form :model="transferForm" :rules="transferRules" ref="transferFormRef" label-width="100px"
        style="display: flex;flex-direction: column;">
        <el-form-item label="单位名:">
          <el-select v-model="transferForm.orgname" style="width: 337px" clearable placeholder="请选择部门" disabled>
            <el-option :label="transferForm.orgname" :value="transferForm.orgname" />
          </el-select>
        </el-form-item>
        <el-form-item label="部门名:" prop="deptId">
          <el-select v-model="transferForm.deptId" style="width: 337px" clearable placeholder="请选择部门">
            <el-option v-for="item in tableData" :key="item" :label="item.deptname" :value="item.deptid"
              @click="changeDept(item)" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="flex just-between">
          <span class="dialog-footer">
            <el-button type="primary" @click="handleSave(transferFormRef)">
              <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>
    <div v-if="addDiaShow" class="dialog-box">
      <Addaqry v-model="addDiaShow" :title="title" :xqdata="xqdata" @changeAddVi="changeAddVi"
        :deptId="props.clickSsdwid" :isSave="isSave" :isUpdate="isUpdate" :rowDeptId="props.deptId"
        :dict="{ D_TB_ZJZLX, D_BZ_XB, D_BZ_AQRYWHCD, D_BZ_AQRYZZMM, D_BZ_AQRYSCLY, D_BZ_SF }" />
    </div>
    <!-- 选择带队领导 -->
    <ChooseUser v-model="chooseUserVisible" :Single="singleShow" :keys="keys" :data="memberList" :deptId="deptId"
      :leaderid="leaderid" @choosedUsers="getSonValue" :searchType="searchType"></ChooseUser>
    <ChooseUser2 v-model="chooseUserVisible2" :Single="singleShow" :keys="keys" :data="memberList" :deptId="deptId"
      :leaderid="leaderid" @choosedUsers="getSonValue" :searchType="searchType"></ChooseUser2>
  </div>
</template>

<script setup>
import * as MOSTY from "@/components/MyComponents/index";
import { onMounted, ref, defineEmits, reactive, getCurrentInstance, defineProps, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import ChooseUser from "@/components/MyComponents/ChooseUser/Leader.vue";
import ChooseUser2 from "@/components/MyComponents/ChooseUser/Leader.vue";
import { getApi, postApi, deleteApi } from "@/api/tobAcco_api.js";
import Addaqry from "./addaqry.vue";
const { proxy } = getCurrentInstance();
const { D_TB_ZJZLX, D_BZ_XB, D_BZ_AQRYWHCD, D_BZ_AQRYZZMM, D_BZ_AQRYSCLY, D_BZ_SF
} = proxy.$dict("D_TB_ZJZLX", "D_BZ_XB", "D_BZ_AQRYWHCD", "D_BZ_AQRYZZMM", "D_BZ_AQRYSCLY", "D_BZ_SF");
const props = defineProps({
  rowId: {
    default: '',
    type: String
  },
  mtcsoltype: {
    default: '',
    type: String
  },
  clickSsdwid: {
    default: '',
    type: String
  },
  deptId: {
    type: String,
    default: '',
  },
  type: {
    type: String,
    default: ''
  },
  orgId: {
    type: String,
    default: '',
  },
  leaderId: {
    type: String,
    default: '',
  },
  orgCode: {
    type: String,
    default: '',
  },
  orgName: {
    type: String,
    default: '',
  },
  tableData: {
    type: Object,
    default: {}
  }
})
const ruleFormRef = ref()
const keys = ref(1)
const searchType = ref("04")
/** 附件列表 */
const Files = ref([])
/** 是否展示附件组件 */
const isShowUpLoad = ref(true)
const rules = reactive({
  executivename: [{ required: true, message: "负责人不能为空", trigger: "blur" }],
  leadershipname: [{ required: true, message: "分管领导不能为空", trigger: "blur" }],
})
const emits = defineEmits(["close"]);
const fromObj = ref({
  ryList: [],
  jzFiles: []
});
const chooseUserVisible = ref(false);//选择领导弹窗
const chooseUserVisible2 = ref(false);//选择领导弹窗
const singleShow = ref(true); //单选多选
const memberList = ref([]); //成员选择的id回显
const deptId = ref(null);//查询当前部门下的人员
const leaderid = ref("");
const editIndex = ref(null);
const zzlx = ref(null);
const xqdata = ref({
})
const addDiaShow = ref(false);//新增弹窗
const title = ref("");
const listQuery = ref({});
const isSave = ref(false)

const tabColumns = reactive([
  {
    title: "安全人员姓名",
    prop: "username"
  },
  {
    title: "性别",
    prop: "xb",
    slot: true
  },
  {
    title: "出生日期",
    prop: "csrq"
  },
  {
    title: "职务",
    prop: "dutyName"
  },
  {
    title: "安全人员类型",
    prop: "aqrylx",
    slot: true
  },
  {
    title: "操作",
    prop: "actions",
    slot: true
  }
])
// 初始化
onMounted(() => {
  // 如果是专职安全部门，查询出部门下的所有人全是安全员
  getDeptData(props.rowId, props.mtcsoltype);
});
const CloseEvent = () => {
  ruleFormRef.value.resetFields();
  emits("close");
};
//查询部门详细资料
function getDeptData(id, mtcsoltype) {
  getApi({ id, mtcsoltype }, '/mosty-jcgl/aqy/getBmDetail').then((res) => {
    fromObj.value = res
    fromObj.value.executivename = res.principalheadname
    fromObj.value.executiveid = res.principalheadid
    fromObj.value.leadershipname = res.fgldname
    fromObj.value.leadershipid = res.fgldid
    deptId.value = fromObj.value.deptid
  })
}
function filehandleChange(fileArr) {
  let jzFiles = fromObj.value.jzFiles
  if (typeof jzFiles === 'string') return // 回显的是字符串，不用保存(回显会触发此方法)
  // 保存数据
  savefrom()
}
/**清空附件 */
function clearFile() {
  if (!fromObj.value.jzFiles.length) return
  isShowUpLoad.value = false
  nextTick(() => {
    isShowUpLoad.value = true
  })
  fromObj.value.jzFiles = []
  // 保存数据
  savefrom()
}
//点击带队领导选择按钮
function ChooesDdld(val) {

  keys.value++
  zzlx.value = val;
  leaderid.value = "";
  // 负责人
  if (val == "01") {
    deptId.value = props.deptId
    leaderid.value = fromObj.value.executiveid;
    chooseUserVisible.value = true;
  }
  // 领导
  if (val == "02") {
    deptId.value = props.orgId
    leaderid.value = fromObj.value.leadershipid;
    // deptId.value = props.leaderId // 只能选领导班子
    chooseUserVisible2.value = true;
    // if (props.type == '02') {
    //   searchType.value = ''
    //   deptId.value = props.orgId
    // }
  }
  singleShow.value = true;
}
const getSonValue = (value) => {
  if (zzlx.value == "01") {
    fromObj.value.executivename = value[0].userName;
    fromObj.value.executiveid = value[0].id;
  }
  if (zzlx.value == "02") {
    fromObj.value.leadershipname = value[0].userName;
    fromObj.value.leadershipid = value[0].id;
  }
  // 保存数据
  savefrom()
};
//保存安全人员信息
const savefrom = () => {
  let params = { ...fromObj.value }
  let jzFiles = Array.isArray(fromObj.value.jzFiles) ? fromObj.value.jzFiles : []
  params.jzFiles = jzFiles.join(",")
  postApi(params, '/mosty-jcgl/aqy/saveAqyInfo').then((res) => {
    ElMessage.success("修改成功");
    addDiaShow.value = false
  })
}
// 修改
const isUpdate = ref(false)
//新增安全人员
function addShow() {
  xqdata.value = {}
  xqdata.value.safeid = fromObj.value.id;
  xqdata.value.departid = fromObj.value.deptid;
  title.value = "安全人员新增";
  isSave.value = true
  isUpdate.value = false
  addDiaShow.value = true;
}
// 查看安全人员
function showRows(row) {
  xqdata.value = row
  xqdata.value.fullTimeYearly = xqdata.value.fullTimeYearly ? Number(xqdata.value.fullTimeYearly) : 0
  xqdata.value.expertise = xqdata.value.expertise ? xqdata.value.expertise.split(',') : null
  title.value = "安全人员查看";
  isSave.value = false
  isUpdate.value = false
  addDiaShow.value = true;
}
// 调岗弹窗
const isShowTransfer = ref(false)
// 调岗弹窗表单ref
const transferFormRef = ref()
// 调岗弹窗表单数据
let transferForm = reactive({
  // 安全信息员数据ID
  id: '',
  // 需调岗安全员ID
  userId: '',
  // 安全部门配置表ID-调岗后
  safeId: '',
  // 单位ID-调岗后
  orgId: '',
  // 单位名
  orgname: '',
  // 部门ID-调岗后
  deptId: '',
  deptname: '',
})
// 表单验证规则
const transferRules = {
  deptId: [
    { required: true, message: '请选择调岗部门', trigger: 'change' }
  ],
}
const changeDept = (data) => {
  transferForm.safeId = data.id
  transferForm.deptname = data.deptname
}
const handleSave = async (transferFormRef) => {
  if (!transferFormRef) return;
  await transferFormRef.validate((valid) => {
    if (valid) {
      postApi(transferForm, "/mosty-jcgl/aqy/transferJob")
        .then((res) => {
          getDeptData(props.rowId, props.mtcsoltype);
          ElMessage.success("调岗成功");
          isShowTransfer.value = false
        })
        .catch(() => {
          ElMessage.success("调岗失败");
        })
    } else {
      ElMessage.error("请输入必填项!");
    }
  });
};
const closed = () => {
  isShowTransfer.value = false
  // if (!transferFormRef.value) return
  // proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
  //   .then(() => {
  //     isShowTransfer.value = fasle
  //   })
  //   .catch(() => {
  //     // catch error
  //   })
};
// 安全人员调岗
function updateTransfer(row) {
  transferForm.id = row.id
  transferForm.userId = row.userid
  transferForm.orgId = props.orgCode
  transferForm.orgname = props.orgName
  isShowTransfer.value = true
}
//修改安全人员
function updateRows(row, index) {
  xqdata.value = row
  xqdata.value.fullTimeYearly = xqdata.value.fullTimeYearly ? Number(xqdata.value.fullTimeYearly) : 0
  xqdata.value.expertise = xqdata.value.expertise ? xqdata.value.expertise.split(',') : null
  title.value = "安全人员修改";
  isSave.value = true
  isUpdate.value = true
  addDiaShow.value = true;
}
//删除安全人员
function delRole(row) {
  deleteApi({}, `/mosty-jcgl/aqy/removeAqy/${row.id}`).then(res => {
    ElMessage.success("删除成功");
    getDeptData(props.rowId, props.mtcsoltype);
  })
}

// 控制新增弹出框的展示
const changeAddVi = (val) => {
  addDiaShow.value = val;
  xqdata.value = {}
  getDeptData(props.rowId, props.mtcsoltype);
};

</script>

<style lang="scss" scoped>
.ld_box {
  display: flex;
  margin-right: 30px;
}

.el-form {
  width: 100%;
  align-items: center;
}

.el-form-item {
  display: flex;
  margin-right: 10px;
}

.addbtn {
  margin-bottom: 10px;
}

.bigBox {
  display: block !important;
  padding: 0 14px;
  box-sizing: border-box;

  .eltabs3 {
    height: calc(100vh - 400px);

    /* 操作列宽度调整 */
    :deep(.custom-operations-table .el-table th.el-table__cell:nth-last-child(2)) {
      width: 300px !important;
      min-width: 300px !important;
    }
  }
}

::v-deep .el-upload-list {
  width: 50%;
}

.fj-label {
  width: 194px;
  display: inline-block;
  line-height: 30px;
  margin-right: 10px;
  color: #000;
}

.clear-icon {
  position: relative;
  top: 1px;
}

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

#btnBoxTetxt {
  color: red;
}
</style>
