<template>
  <basic-container>
    <el-drawer
      title="重点人群推送"
      append-to-body
      :visible.sync="drawer"
      size="60%"
      class="drawer"
    >
      <avue-crud
        :option="personListOption"
        :table-loading="loading"
        :data="data"
        :page.sync="page"
        ref="crud"
        :permission="permissionList"
        @search-change="searchChange"
        @search-reset="searchReset"
        @selection-change="selectionChange"
        @current-change="currentChange"
        @size-change="sizeChange"
        @refresh-change="refreshChange"
        class="customPage"
        @on-load="onLoad"
      >
        <!--自定义列-->
        <template slot="resume" slot-scope="{ row }">
          <div>
            <el-button
              type="text"
              @click="$refs.resume.openDialog(row)"
              v-if="row.userId && row.userId !== '0'"
              >查看简历</el-button
            >
            <div v-else>暂无简历</div>
          </div>
        </template>
        <template slot="recommend" slot-scope="{ row }">
          <div>
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-plus"
              @click="rowRecommend(row)"
              v-if="row.isApply === 0 && row.telphone != ''"
              >邀请</el-button
            >
            <!-- v-show="row.isApply === 1 && row.telphone == ''" -->
            <el-button
              type="info"
              disabled
              size="mini"
              icon="el-icon-plus"

              v-else
              style="margin-left: 0px"
              >邀请</el-button
            >

            <!-- <el-button type="primary" size="mini" disabled v-show="row.count>=2">已邀请</el-button> -->
          </div>
        </template>
        <template slot="count" slot-scope="{ row }">{{
          2 - row.count
        }}</template>
        <!--自定义按钮-->
        <template slot="menuLeft">
          <el-button
            type="primary"
            size="small"
            :disabled="!selectionList.length"
            icon="el-icon-plus"
            @click="handleRecommend"
            >批量邀请</el-button
          >
        </template>
        <template slot="menuRight">
          <el-button
            type="primary"
            size="small"
            @click="handleExport"
            >导出</el-button
          >
        </template>
        <template v-slot:idNumber="{row}">
          <span>{{idNumberDDesensitization(row.idNumber)}}</span>
        </template>
        <template slot="name" slot-scope="{row}">
          <span v-if="row.status==1">{{row.name}}</span>
            <span v-else>{{row.name}}（<span style="color: red;">未注册</span>）</span>

        </template>
        <!--/自定义按钮-->
      </avue-crud>
      <Resume ref="resume"></Resume>
    </el-drawer>
  </basic-container>
</template>

<script>
import { getCommendList, inviteCount,inviteUser,recommendExportList } from "@/api/tenant/postzp";
import Resume from "@/components/resume/index";
import { mapGetters } from "vuex";
import { idNumberDDesensitization } from "@/util/util";

export default {
  data () {
    return {
      isIndeterminate: false,
      checkAll: false,
      checked: false,
      missionId: "",
      missionTitle: "",
      stime: "",
      drawer: false,
      selectionList: [],
      loading: false,
      query: {},
      page: {
        pageSize: 100,
        currentPage: 1,
        total: 0,
      },
      personListOption: {
        height: "auto",
        dialogWidth: "30%",
        align: "center",
        menuAlign: "center",
        rowKey: "id",
        tip: false,
        menu: false,
        addBtn: false,
        columnBtn: false,
        searchBtn: true,
        searchShow: true,
        searchMenuSpan: 6,
        searchLabelWidth: 60,
        menuPosition: "center",
        labelPosition: "right",
        border: true,
        index: true,
        indexLabel: "序号",
        selection: true,
        selectable: function (row) {
          return row.isApply === 0;
        },
        viewBtn: false,
        dialogType: "dialog",
        dialogClickModal: false,
        column: [
          {
            label: "姓名",
            prop: "name",
            search: true,
            span: 24,
            width:155,
            rules: [
              {
                required: true,
                whitespace: true,
                message: "请输入姓名",
                trigger: "blur",
              },
            ],
            slot:true,
          },
          {
            label: "性别",
            prop: "sex",
            search: false,
            span: 24,
            dicData: [
              {
                label: "男",
                value: 1,
              },
              {
                label: "女",
                value: 2,
              },
            ],
          },
          {
            label: "年龄",
            prop: "age",
            search: false,
            span: 24,
          },
          {
            label: "身份证",
            prop: "idNumber",
            search: false,
            span: 24,
            width:150,
            slot: true
          },
          // {
          //   label: "工种",
          //   type: "tree",
          //   prop: "worktypes",
          //   multiple: true,
          //   dicUrl: `/api/jobslink-api/tenant/worktypes/base/list`,
          //   dicFormatter: (res) => {
          //     return res.data; //返回字典的层级结构
          //   },
          //   props: {
          //     label: "name",
          //     value: "name",
          //   },
          //   search: true,
          //   span: 24,
          // },
          {
            label: "重点人群库",
            prop: "groupId",
            type: "tree",
            span: 24,
            search: true,
            display: true,
            width: '200',
            dicUrl: `/api/jobslink-api/tenant/talents/group/listAll`,
            dicFormatter: (res) => {
              return res.data.list; //返回字典的层级结构
            },
            props: {
              label: "groupName",
              value: "id",
            },
            placeholder: "请选择分组",
          },
          // {
          //   label: "简历",
          //   prop: "resume",
          //   slot: true,
          //   display: false
          // },
          {
            label: "剩余邀请次数",
            prop: "count",
            slot: true,
            width: 150,
          },
          {
            label: "操作",
            prop: "recommend",
            slot: true,
          },

        ],
      },
      excelBox: false,
      data: [],
    };
  },
  components: {
    Resume,
  },
  watch: {},
  computed: {
    ...mapGetters(["userInfo", "permission"]),
    // permissionList() {
    //   return {
    //     addBtn: this.vaildData(this.permission.user_add, false),
    //     viewBtn: this.vaildData(this.permission.user_view, false),
    //     delBtn: this.vaildData(this.permission.user_delete, false),
    //     editBtn: this.vaildData(this.permission.user_edit, false)
    //   };
    // },
    ids () {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.userId);
      });
      return ids.join(",");
    },
    phones () {
      let phones = [];
      this.selectionList.forEach((ele) => {
        phones.push(ele.telphone);
      });
      return phones.join(",");
    },
  },
  methods: {
    idNumberDDesensitization,
    //导出
    handleExport(){
      window.open(recommendExportList(this.missionId,this.query.name?this.query.name:"",this.query.worktypes?this.query.worktypes:"",this.query.groupId?this.query.groupId:""));
    },
    /*打开drawer*/
    openDialog (row) {
      this.missionId = row.missionNo;
      this.missionTitle = row.missionTitle;
      this.stime = row.stime;
      if (this.$refs.crud) {
        this.$refs.crud.searchReset();
      } else {
        this.query = {};
        this.onLoad(this.page, this.query);
      }
      this.drawer = true;
    },
    /*邀请人才 */
    rowRecommend (row) {
      const h = this.$createElement;
      let count = 2 - row.count;
      this.$confirm(
        h("div", null, [
          h(
            "p",
            { style: "font-size: 16px" },
            "您确定要向" + row.name + "发送邀请吗? "
          ),
          h(
            "p",
            { style: "color: red" },
            "每个人最多邀请2次，还剩" + count + "次"
          ),
        ]),
        {
          type: "warning",
          showClose: false,
          showCancelButton: true,
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          beforeClose: (action, instance, done) => {
            if (action === "confirm") {
              instance.confirmButtonLoading = true;
              instance.cancelButtonLoading = true;
              instance.closeOnPressEscape = false;
              instance.closeOnClickModal = false;
              setTimeout(() => {
                done();
                setTimeout(() => {
                  instance.confirmButtonLoading = false;
                  instance.cancelButtonLoading = false;
                }, 300);
              }, 1000);
            } else {
              done();
            }
          },
        }
      )
        .then(() => {
          let rows = [];
          rows.push({
            idNumber: row.idNumber,
            missionNo: this.missionId,
            missionTitle: this.missionTitle,
            telphone: row.telphone,
          });
          inviteUser(rows).then(
            () => {
              this.$message({
                type: "success",
                message: "操作成功!",
              });
              this.onLoad(this.page);
            },
            (error) => {
              window.console.log(error);
            }
          );
        })
        .catch(() => {
          // this.$message({
          //   type: 'info',
          //   message: '已取消'
          // });
        });
    },
    /*批量邀请人才*/
    handleRecommend () {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      const h = this.$createElement;
      this.$confirm(
        h("div", null, [
          h("p", { style: "font-size: 16px" }, "您确定要批量发送邀请吗? "),
          h("p", { style: "color: red" }, "每个人最多邀请2次"),
        ]),
        {
          type: "warning",
          showClose: false,
          showCancelButton: true,
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          beforeClose: (action, instance, done) => {
            if (action === "confirm") {
              instance.confirmButtonLoading = true;
              instance.cancelButtonLoading = true;
              instance.closeOnPressEscape = false;
              instance.closeOnClickModal = false;
              setTimeout(() => {
                done();
                setTimeout(() => {
                  instance.confirmButtonLoading = false;
                  instance.cancelButtonLoading = false;
                }, 300);
              }, 1000);
            } else {
              done();
            }
          },
        }
      )
        .then(() => {
          let rows = [];
          this.selectionList.forEach((ele) => {
            rows.push({
              idNumber: ele.idNumber,
              missionNo: this.missionId,
              missionTitle: this.missionTitle,
              telphone: ele.telphone,
            });
          });
          inviteUser(rows).then(
            () => {
              this.$message({
                type: "success",
                message: "操作成功!",
              });
              this.onLoad(this.page);
            },
            (error) => {
              window.console.log(error);
            }
          );
        })
        .catch(() => {
          // this.$message({
          //   type: 'info',
          //   message: '已取消'
          // });
        });
    },
    searchReset () {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange (params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, this.query);
      done();
    },
    selectionChange (list) {
      this.selectionList = list;
    },
    selectionClear () {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange (currentPage) {
      this.page.currentPage = currentPage;
      this.onLoad(this.page);
    },
    sizeChange (pageSize) {
      this.page.currentPage = 1;
      this.page.pageSize = pageSize;
      this.onLoad(this.page);
    },
    refreshChange () {
      this.onLoad(this.page, this.query);
    },
    onLoad (page, params = {}) {
      this.loading = true;
      getCommendList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query),
        this.missionId
      ).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        if (this.data.length > 0) {
          for (let i = 0; i < this.data.length; i++) {
            inviteCount(this.data[i].idNumber, this.missionId).then((res) => {
              this.$set(this.data[i], "count", res.data.data.count); //count为已邀请次数 2-count为剩余邀请次数
              this.$set(this.data[i], "isApply", res.data.data.isApply); //isApply===0 可邀请，===1不可邀请
            });
          }
        }

        this.loading = false;
        this.selectionClear();
      });
    },
  },
};
</script>
