<template>
  <div>
    <MOSTY.PageTree :pageTitle="'人才库管理'" :searchType="'01'" @getDeptId="getdeptData">
      <template #titleright>
        <!-- 头部 -->
        <div class="headBox" style="justify-content: space-between">
          <div class="toggle" :class="{ active: isOpen }" @click="showTotalClick">
            <span>统计</span>
            <el-icon>
              <DArrowLeft />
            </el-icon>
          </div>
        </div>
      </template>
      <template #serach>
        <!-- 统计后面备用 -->
        <!-- <section v-show='isOpen' ref="getHeight">
          <section class="box-sjtj" style="height: 100px;">
            <section class="flex">
              <section  class="left-tj">
                <Sjtj :info="countData" :isShowTip="false" :isShowBottom="false" :width="236" mb="6px" />
              </section>
            </section>
          </section>
        </section>
        <el-divider /> -->
        <div class="box">
          <div class="flxbox">
            <el-input v-model="listQuery.userName" clearable placeholder="请输入人员姓名进行查询" style='width: 250px;'
              class="mr20" />
            <el-select v-model="listQuery.type" clearable placeholder="请选择人才类型进行查询" style='width: 250px;' class="mr20">
              <el-option v-for="obj in D_BZ_RCLX" :key="obj.value" :label="obj.label" :value="obj.value" />
            </el-select>
            <el-select v-if="listQuery.type == '02'" v-model="listQuery.level" clearable placeholder="请选择等级"
              style='width: 250px;'>
              <el-option v-for="obj in D_BZ_ZCXFGCSJB" :key="obj.value" :label="obj.label" :value="obj.value" />
            </el-select>
            <el-select v-if="listQuery.type == '01'" v-model="listQuery.level" clearable placeholder="请选择等级"
              style='width: 250px;'>
              <el-option v-for="obj in D_BZ_ZCAQGCSJB" :key="obj.value" :label="obj.label" :value="obj.value" />
            </el-select>
          </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" :style="{ height: tableHeights }">
          <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 #actions="{ row }">
              <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 v-model="dialogVisible" :title="pageData.fromObj.id ? '修改' : '新增'" width="80%" append-to-body
      :before-close="closeDialog">
      <el-form class="mosty-from-wrap" ref="ruleFormRef" label-width="130px" :model="pageData.fromObj" :inline="true"
        :rules="rules" style="flex-wrap: wrap;">
        <el-form-item label="人员姓名:" prop="userName" style="width: 100%;">
          <el-input v-model="pageData.fromObj.userName" clearable placeholder="请选择人员" readonly
            @click="chooseUserVisible = true">
            <template #append>
              <div @click="onClickAdd">添加类型</div>
            </template>
          </el-input>
        </el-form-item>

        <!-- <el-form-item label="是否聘任：" prop="hireFlag" style="width: 45%">
          <MOSTY.DictRidioAndSelect :dictData="D_BZ_SF" v-model="pageData.fromObj.hireFlag" selectType="radio"
            :disabled="false" style="width: 100%;" />
        </el-form-item> -->
        <el-form-item label="人才类型:" prop="list" style="width: 100%;">
          <div v-for="(item, index) in pageData.fromObj.list" :key="item" class="flex flex-warp ww49">
            <div class="mb10 ww100 flex just-between">
              <MOSTY.DictRidioAndSelect :dictData="D_BZ_RCLX" v-model="item.type" selectType="select"
                @onChange="item.level = null" placeholder="请选择人才类型"
                :style="{ width: ['01', '02'].includes(item.type) ? '30%' : '45%' }" />
              <MOSTY.DictRidioAndSelect :dictData="D_BZ_ZCXFGCSJB" v-model="item.level" selectType="select"
                placeholder="请选择等级" style="width:30%" v-if="['02'].includes(item.type)" />
              <MOSTY.DictRidioAndSelect :dictData="D_BZ_ZCAQGCSJB" v-model="item.level" selectType="select"
                placeholder="请选择等级" style="width:30%" v-if="['01'].includes(item.type)" />
              <el-date-picker v-model="item.date" :style="{ width: ['01', '02'].includes(item.type) ? '30%' : '45%' }"
                type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD" placeholder="请选择取证时间"
                :disabled-date="disablednowDate1" />
              <el-icon @click="cancelRclx(index)" :size="22" style="cursor: pointer;">
                <CloseBold />
              </el-icon>
            </div>


            <div class='mr10' style='color:red;line-height: 162px;margin-left:-75px;'>*<span
                style='color:#000;'>上传图片:</span></div>
            <MOSTY.Upload width="100%" :nopicer="false" :isImg="true" v-model="item.files" :limit="2"
              gsgfList="[PNG,JPG]" :nameshow="true"></MOSTY.Upload>

          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">

          <el-button @click="savefrom(ruleFormRef)" :loading="addLoading"> <el-icon>
              <DocumentChecked />
            </el-icon>
            <span>保存</span></el-button>
          <el-button @click="closeDialog"> <el-icon>
              <DocumentDelete />
            </el-icon>
            <span>关闭</span></el-button>

        </span>
      </template>
    </el-dialog>
    <ChooseUser v-model="chooseUserVisible" :data="memberList" :deptId="deptId" :leaderid="leaderid"
      @choosedUsers="getSonValue"></ChooseUser>
  </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 { exportXlsx } from "@/excel/Export2Excel.js";
import { disablednowDate1 } from "@/utils/tools.js";
import Sjtj from '@/views/dataReportWork/aqjypx/components/sjtj.vue'
import {
  ref,
  onMounted,
  getCurrentInstance,
  reactive,
  computed
} 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 isOpen = ref(false);
const tableColumn = ref([
  {
    title: "所属单位",
    prop: "orgName",
  },
  {
    title: "所属部门",
    prop: "deptName"
  },
  {
    title: "人员姓名",
    prop: "userName"
  },
  {
    title: "人才类型",
    prop: "type",
    slot: true
  },
  {
    title: "操作",
    prop: "actions",
    slot: true
  }
])
const pageConfiger = reactive({
  pageSize: 20,
  pageCurrent: 1,
  total: 0
})
const dialogVisible = ref(false)
const tableLoading = ref(false)
const deptId = ref(null);
const leaderid = ref("");
const chooseUserVisible = ref(false)
const addLoading = ref(false)
const tableloading = ref(false)
const memberList = ref([]);//默认选中的人员
const tableHeights = ref('calc(100% - 235px)')
//证书校验
const validateArray = (rule, value, callback) => {
  if (!Array.isArray(value)) {
    return callback(new Error('必须是一个数组'));
  }
  for (let i = 0; i < value.length; i++) {
    if (value[i]) {
      if (!value[i].type) {
        return callback(new Error(`请选择人才类型`));
      } else if (!value[i].date) {
        return callback(new Error(`请选择取证时间`));
      } else if (!value[i].files) {
        return callback(new Error(`请上传附件`));
      } else if (!value[i].level) {
        if (["01", "02"].includes(value[i].type)) {
          return callback(new Error(`请选择等级`));
        }
      }
    } else {
      return callback(new Error(`请选择类型与等级，并上传附件`));
    }
  }
  callback();
};
const rules = ref({
  userName: [{ required: true, message: "请选择人员", trigger: "change" }],
  time: [{ required: true, message: "请选择取证时间", trigger: "change" }],
  // hireFlag: [{ required: true, message: "请选择是否聘任", trigger: "change" }],
  list: [{ required: true, validator: validateArray, trigger: 'blur' }],
});
const ruleFormRef = ref()
//查询参数
const total = ref(0);
const listQuery = ref({
  pageCurrent: 1,
  pageSize: 10,
});

/** 统计数组 */
const countData = ref([
  { title: '总数', num: 0, dm: '', icon: 'ccss/icon_01.png' },
  { title: '警告类标识', num: 0, dm: '200301000000', icon: 'ccss/icon_02.png' },
  { title: '禁止类标识', num: 0, dm: '200302000000', icon: 'ccss/icon_03.png' },
  { title: '指令类标识', num: 0, dm: '200303000000', icon: 'ccss/icon_04.png' },
  { title: '提示类标识', num: 0, dm: '200304000000', icon: 'ccss/icon_05.png' },
])

const showTotalClick = () => {
  isOpen.value = !isOpen.value
  let countHeight = isOpen.value ? 100 : 0 //展开高度 100 ，关闭：0
  tableHeights.value = `calc(100% - 235px - ${countHeight}px)`
}
const pageData = reactive({

  fromObj: {
    userId: "",
    //人才类型
    list: [{
      type: "",
      level: "",
      files: ""
    }],
  },

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

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




//取消证书
const cancelRclx = index => {
  if (pageData.fromObj.list.length == 1) {
    proxy.$message.warning("必须保留一条人才类型")
    return
  }
  pageData.fromObj.list.splice(index, 1)
}
//添加人员类型
const onClickAdd = () => {
  pageData.fromObj.list.push({
    type: "",
    level: "",
    files: ""
  })
}
//选中人员数据
const getSonValue = (val) => {
  const { id, userName } = val[0]
  pageData.fromObj = { ...pageData.fromObj, userId: id, userName }
}
// 获取数据的方法
const getListData = async () => {
  tableLoading.value = true
  getApi(listQuery.value, "/mosty-jcgl/talents/selectPageOfTalents").then(res => {
    if (res) {
      // total.value = res.total
      pageConfiger.total = res.total
      for (let i = 0; i < res.records.length; i++) {
        res.records[i].type = res.records[i].type.split(",")
      }
      tableData.value = res.records;
    }
  }).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.type = '';
  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) => {
  pageData.fromObj = {
    list: [{
      type: "",
      level: "",
      files: ""
    }],
  };
  dialogVisible.value = true;
};

const closeDialog = () => {
  proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
    .then(() => {
      dialogVisible.value = false;
    })
    .catch(() => {
      // catch error
    })

};
//新增人员
const savefrom = (elform) => {
  addLoading.value = true
  elform.validate((valid) => {
    if (valid) {
      let url = "/mosty-jcgl/talents/addTalent"
      if (pageData.fromObj.id) url = "/mosty-jcgl/talents/updateTalent"
      for (let i = 0; i < pageData.fromObj.list.length; i++) {
        const item = pageData.fromObj.list[i]
        try {
          item.files = item.files.join(",")
        } catch (error) {

        }
      }
      postApi(pageData.fromObj, url).then(res => {
        proxy.$message.success("成功")
        getListData()
        dialogVisible.value = false;
      }).finally(() => {
        addLoading.value = false
      })
    } else {
      addLoading.value =
        ElMessage.error("请输入必填项!");
      return false;
    }
  });
};
//编辑
const clickEdit = (row) => {
  getApi({ id: row.id }, "/mosty-jcgl/talents/selectTalentsByID").then(res => {
    if (res) pageData.fromObj = res
    dialogVisible.value = true
  })

}
const deldete = (row) => {
  deleteApi({}, `/mosty-jcgl/talents/delTalent/${row.id}`).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>
.headBox {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .toggle {
    height: 40px;
    cursor: pointer;
    display: flex;
    align-items: center;
    color: #0f3916;

    .el-icon {
      transform: rotate(90deg);
      transition: all 0.25s ease;
    }

    &.active {
      .el-icon {
        transform: rotate(-90deg);
      }
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: center;
  text-align: center;
}

.treeBox {
  overflow: auto;
}

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

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