<template>
  <div class="ContainerBox tableAlign">
    <!-- 备注区域 -->
    <section class="remarkBox">
      <div class="remarkInfo">
        <i class="el-icon-warning-outline el-icon-flag"></i>
        <span>
          1.
          待确认人员为通过“邀请入职”或“邀请驻勤”方式，由人员自行填写信息并提交。
          2.您可以对待确认的人员做入职确认，确认入职后该人员将自动完成入职。
        </span>
      </div>
    </section>
    <!-- 按钮区域 -->
    <section class="buttonBox">
      <el-row>
        <el-col :span="6">
          <el-button type="primary" @click="preBt">批量确认</el-button>
          <el-button type="danger" @click="batch(2)">批量拒绝</el-button>
        </el-col>
        <el-col :span="18">
          <el-form
            :inline="true"
            :model="params"
            ref="ruleForm"
            label-width="130px"
            label-position="right"
          >
            <el-form-item label="部门" prop="departIds">
              <selectTree
                placeholder="请选择部门"
                ref="selectTree"
                @getValue="checkChange"
                :curValue="params.departIds"
                :data="tableData"
                :obj="{
                  id: 'id',
                  label: 'name',
                  children: 'children',
                }"
                checkStrictly
                clearable
                filterable
                multiple
                collapseTags
              ></selectTree>
            </el-form-item>

            <el-form-item label="职业类型" prop="occupationTypes">
              <el-select
                v-model="params.occupationTypes"
                multiple
                collapse-tags
                clearable
                placeholder="请选择职业类型"
                style="width: 100%"
                @change="changeoccupationTypes"
              >
                <el-option
                  v-for="(item, index) in occupationTypeArr"
                  :label="item.label"
                  :value="item.value"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="" prop="keyword">
              <el-input
                v-model="params.keyword"
                placeholder="姓名/手机号/证件号"
                clearable
              />
            </el-form-item>
            <el-form-item label="" prop="occupationTypes">
              <el-button type="primary" @click="query()">查询</el-button>
              <el-button @click="reset()">重置</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </section>
    <!-- 选中表格内容展示区域 -->
    <section class="TableSelectBox" v-if="multipleSelection.length">
      <span
        ><i class="el-icon-warning-outline el-icon-flag"></i>已选中：<span
          v-for="(item, index) in multipleSelection"
          :key="index"
          >{{ item.name
          }}<b v-if="index != multipleSelection.length - 1">,</b></span
        ></span
      >
    </section>
    <!-- 内容区域 -->
    <section class="contentBox">
      <el-table
        :data="list"
        ref="districtTable"
        max-height="500"
        default-expand-all
        row-key="id"
        :expand-row-keys="expandRow"
        @selection-change="handleSelectionChange"
        @select-all="handleSelectionAllChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <!-- <el-table-column prop="id" label="id" width=""></el-table-column> -->
        <el-table-column prop="name" label="姓名" width=""></el-table-column>
        <el-table-column
          prop="telephone"
          label="手机号"
          width=""
        ></el-table-column>
        <el-table-column
          prop="credentialType"
          label="证件类型"
          width=""
        ></el-table-column>
        <el-table-column
          prop="credentialNumber"
          label="证件号码"
          width=""
        ></el-table-column>
        <el-table-column
          prop="inviter.name"
          label="邀请人"
          width=""
        ></el-table-column>
        <el-table-column
          prop="inviter.createdTime"
          label="邀请时间"
          width=""
        ></el-table-column>
        <el-table-column
          prop="departmentName"
          label="邀请入职部门"
          width=""
        ></el-table-column>
        <el-table-column prop="occupationType" label="职业类型" width="">
        </el-table-column>

        <el-table-column
          prop="invitedType"
          label="邀请类型"
          width=""
        ></el-table-column>

        <el-table-column
          prop="attendanceSiteName"
          label="邀请驻勤点"
          width=""
        ></el-table-column>
        <el-table-column label="操作" fixed="right" align="center" width="200">
          <template slot-scope="scope">
            <el-button
              @click="editDept(scope.row, 1)"
              type="text"
              size="small"
              class="primaryColor"
              >确认入职</el-button
            >
            <el-button
              @click="editDept(scope.row, 2)"
              type="text"
              size="small"
              class="primaryColor"
              >拒绝入职</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <pages
        :total="params.total"
        :currentPage.sync="params.pageIndex"
        :pageSize="params.pageSize"
        @handleCurrentChangeSub="handleCurrentChange"
        @handleSizeChangeSub="handleSizeChange"
      ></pages>
    </section>
    <el-dialog
      title="选择部门"
      :visible="dpVis"
      :modal-append-to-body="false"
      append-to-body
      class="el-dialog-single"
      width="25%"
      :before-close="() => (dpVis = false)"
    >
      <div style="padding: 30px; height: 25vh">
        <selectTree
          placeholder="请选择部门"
          ref="selectTree1"
          @getValue="cdpCheckChange"
          :curValue="cdpDepartIds"
          :data="tableData"
          :obj="{
            id: 'id',
            label: 'name',
            children: 'children',
          }"
          checkStrictly
          clearable
          filterable
          collapseTags
        ></selectTree>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmDp">确 定</el-button>
        <el-button @click="dpVis = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="确认入职"
      :visible="cdm"
      :modal-append-to-body="false"
      append-to-body
      class="el-dialog-single"
      width="25%"
      :before-close="() => (cdm = false)"
    >
      <div style="padding: 30px">
        <section class="TableSelectBox">
          <span
            ><i class="el-icon-warning-outline el-icon-flag"></i
            >当前已选择已选中：<span v-for="(item, index) in zmp" :key="index"
              >【{{ item.name }}】 <b v-if="index != zmp.length - 1">,</b></span
            >
            <span style="color: red">（{{ zmp.length }}）</span>
            人入职以下部门</span
          >
        </section>
        <div style="margin-top: 16px; font-weight: bold; text-align: left">
          {{ cdpV.name }}
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmsr">确 定</el-button>
        <el-button @click="()=>cdm = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import selectTree from "@/components/SelectTree";
import {
  StaffDepartmentListApi,
  getruzhilist,
  getruzhiqueren,
} from "@/api/staffApi.js";
export default {
  components: {
    selectTree, //注册组件
  },
  data() {
    return {
      cdpDepartIds: "",
      dpVis: false,
      params: {
        keyword: "",
        departIds: [],
        occupationTypes: [],
        pageIndex: 1, //当前页码
        pageSize: 10, //每页显示多少条
      },
      value: "",
      search: "",
      expandRow: [],
      multipleSelection: [], //全选列表
      tableData: [],
      list: [
        { label: "一般职员", value: "Normal", id: "1" },
        { label: "保安员", value: "SecurityGuard", id: "2" },
        { label: "警官", value: "Police", id: "3" },
      ],
      occupationTypeArr: [
        { label: "一般职员", value: "Normal" },
        { label: "保安员", value: "SecurityGuard" },
      ],
      ids: [], // 批量操作的时候 存放IDS
      zmp: [],
      cdm: false,
      cdpV: {},
    };
  },
  mounted() {
    this.getdata();
    this.tableDatalist(); //查询部门列表
  },
  watch: {
    multipleSelection() {
      //复选框选中启用按钮
      if (this.multipleSelection.length) {
        this.disabled = false;
      } else {
        this.disabled = true;
      }
    },
  },
  methods: {
    confirmDp() {
      console.log(this.cdpDepartIds);
      if (this.cdpDepartIds.length == 0) {
        this.$message({ type: "error", message: "请先选择部门" });
        return;
      }
      this.cdm = true;
    },
    confirmsr() {
      this.$confirm("确认入职后人员将自动完成入职，是否继续操作", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          
          getruzhiqueren({
            ids: this.zmp.map((e) => e.id),
            invitedStatus: "Agree",
            departId: this.cdpDepartIds,
          }).then((res) => {
            console.log('getruzhiqueren11', res)
            // 失败会在拦截器那边提示的
            if (res.status == 200) {
              this.$message({ type: "success", message: "操作成功" });
              this.getdata();
              this.cdpV = {};
              this.dpVis = false;
              this.cdm = false;
              this.zmp = [];
            }
          });
        })
        .catch((error) => {
          console.log('getruzhiqueren11', error);
        });
    },
    handleCurrentChange(val) {
      //分页切换页码
      this.params.pageIndex = val;
      this.getdata();
    },
    handleSizeChange(val) {
      //切换每页条数
      this.params.pageIndex = 1; //重置第一页
      this.params.pageSize = val;
      this.getdata();
    },
    query() {
      this.getdata();
    },
    reset() {
      this.$refs["ruleForm"].resetFields();
    },
    checkChange(key, data) {
      //selectTree组件-复选框选中的数据
      this.$set(this.params, "departIds", key);
      this.defaulData = this.params.departIds;
    },
    cdpCheckChange(key, r) {
      this.cdpDepartIds = key;
      this.cdpV = r;
      console.log(r);
    },
    getdata() {
      getruzhilist(this.params).then((res) => {
        if (res.status == 200) {
          this.params.total = res.data.total;
          this.list = res.data.data;
        }
      });
    },
    // 下拉框 初始化的时候 获取数据 显示下拉数据
    tableDatalist() {
      //部门列表-表格列表
      let obj = { domainId: this.$route.query.domainId }; //获取url域domainId
      StaffDepartmentListApi(obj).then((response) => {
        if (response.data) {
          this.tableData = response.data;
          // this.sortTableData(this.tableData);
        }
      });
    },
    changeoccupationTypes() {
      this.$nextTick(() => {
        this.$forceUpdate();
      });
    },
    handleSelectionChange(val) {
      //选中全选
      this.multipleSelection = val;
    },
    handleSelectionAllChange(selection, first) {
      //全选
      if (!first) {
        this.isAllSelect = !this.isAllSelect;
      }
      selection.map((el) => {
        if (el.children) {
          el.children.map((j) => {
            this.toggleSelection(j, this.isAllSelect);
          });
          if (el.children.length > 0) {
            this.handleSelectionAllChange(el.children, true);
          }
        }
      });
    },

    preBt() {
      if (this.multipleSelection.length == 0) {
        this.$message({ type: "error", message: "请先勾选项目" });
        return;
      }
      console.log(this.list, this.multipleSelection);
      const res1 = this.multipleSelection.filter(
        (ex) => ex.invitedType === "政务网申报"
      );
      const res2 = this.multipleSelection.filter(
        (ex) => ex.invitedType != "政务网申报"
      );

      if (res1.length && res2.length) {
        this.$message({
          type: "error",
          message: "您选择了多条数据中邀请类型，请重新选择",
        });
        return;
      }

      if (res1.length) {
        this.zmp = [...res1];
        return (this.dpVis = true);
      }
      if (res2.length) {
        this.batch(1);
      }
    },
    // 批量确认或者
    batch(type) {
      if (this.multipleSelection.length == 0) {
        this.$message({ type: "error", message: "请先勾选项目" });
        return;
      }
      this.ids = this.multipleSelection.map((item) => item.id);
      this.do(type);
    },
    editDept(row, type) {
      this.ids = [row.id];
      if (row.invitedType === "政务网申报"&&type===1) {
        this.zmp = [{ ...row }];
        return (this.dpVis = true);
      }
      this.do(type);
    },
    do(type) {
      let tips = "";
      let t = "";
      if (type == 1) {
        tips = "确认入职后人员将自动完成入职，是否继续操作";
        t = "Agree";
      } else {
        tips = "拒绝入职后人员将清除该记录，是否继续操作";
        t = "Refuse";
      }
      let data2 = {
        ids: this.ids,
        invitedStatus: t,
      };
      this.$confirm(tips, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          getruzhiqueren(data2).then((res) => {
            console.log('getruzhiqueren22', res)
            // 失败会在拦截器那边提示的
            if (res.status == 200) {
              this.$message({ type: "success", message: "操作成功" });
              this.getdata();
            }
          }).catch((error) => {
          console.log('getruzhiqueren22', error.data);
          if(error.code==1000600 && error.data.length > 0) { //提醒确认入职
              let err1 = error.data.find((item) => item.code == 1000601)
              let err2 = error.data.find((item) => item.code == 1000602)
              if (err1 || err2) {
                console.log('err1err1err1err1err1err1err1err1err1err1err1', err1, err2)
                let errPerSons1 = this.list.filter((it) => err1?.ids.includes(it.id)).map((it) => it.name)
                let errPerSons2 = this.list.filter((it) => err2?.ids.includes(it.id)).map((it) => it.name)
                console.log('errPerSons', errPerSons1, errPerSons2)
                let tip1 = err1?.ids.length > 0 ? `<span>${errPerSons1.join(",")}为从业异常人员，是否确认录用！</span>` : ""
                let tip2 = err2?.ids.length > 0 ? `<span>${errPerSons2.join(",")}不符合担任保安员，无法录入系统！</span>` : ""
                this.$confirm(`${tip2}<br>${tip1}`, "提示", {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "warning",
                  showConfirmButton: tip1 ? true : false,
                  dangerouslyUseHTMLString: true
                }).then(() => {
                  console.log('thenthen', tip1, tip2)
                  if (!tip1 && tip2) {
                    return
                  } else if (tip1 && !tip2) {
                    let data3 = {
                      ids: this.ids,
                      invitedStatus: t,
                      abnormalPersonnelConfirm : true
                    };
                    getruzhiqueren(data3).then((res) => {
                      if (res.status == 200) {
                        this.$message({ type: "success", message: "操作成功" });
                        this.getdata();
                      }
                    })
                  } else if (tip1 && tip2) {
                    let data3 = {
                      ids: this.ids.filter(v => err2?.ids.indexOf(v)==-1),
                      invitedStatus: t,
                      abnormalPersonnelConfirm : true
                    };
                    getruzhiqueren(data3).then((res) => {
                      if (res.status == 200) {
                        this.$message({ type: "success", message: "操作成功" });
                        this.getdata();
                      }
                    })
                  }
                })
              }
            }
        });;
        })     
    },
  },
};
</script>
<style lang="scss">
.el-dialog-single {
  padding: 24px;
}
.ContainerBox {
  .el-table tr td.is-left {
    text-align: left !important;
  }
  .remarkBox {
    .remarkInfo {
      background: #fafafa;
      color: #666666;
      border: 1px solid #ebeef5;
      border-radius: 4px;
      line-height: 30px;
      padding: 10px;
      display: flex;
      .el-icon-flag {
        margin-top: 9px;
        color: #ffc108;
        margin-right: 10px;
      }
    }
  }
  .primaryColor {
    color: #108ee9;
  }
  .dangerColor {
    color: red;
  }
  .bluelink {
    color: #409eff;
    cursor: pointer;
  }
  .TableSelectBox {
    display: flex;
    background: #e6f3fc;
    color: #666666;
    border: 1px solid #d4f0fc;
    border-radius: 4px;
    margin-top: 10px;
    margin-bottom: 10px;
    padding: 5px 0;
    span {
      padding: 0 5px;
      line-height: 20px;
      i {
        margin-left: 5px;
        margin-right: 5px;
        color: #2e8ad7;
      }
    }
  }
}
</style>
