<template>
  <el-row>
    <el-col :span="5">
      <company-tree @node-click="nodeClick"></company-tree>
    </el-col>
    <el-col :span="19">
      <basic-container>
        <avue-crud
          :data="data"
          :table-loading="loading"
          :option="option"
          ref="crud"
          v-model="form"
          :permission="permissionList"
          :before-open="beforeOpen"
          :before-close="beforeClose"
          :page.sync="page"
          @row-update="rowUpdate"
          @row-save="rowSave"
          @row-del="rowDel"
          @search-change="searchChange"
          @search-reset="searchReset"
          @selection-change="selectionChange"
          @current-change="currentChange"
          @size-change="sizeChange"
          @refresh-change="refreshChange"
          @on-load="onLoad"
        >
          <template slot="menuLeft">
            <el-button
              type="primary"
              size="small"
              v-if="vaildData(permission.manage_company_worktypes_add, false)"
              icon="el-icon-plus"
              @click="handleAdd"
              :disabled="!companyId"
              >新增</el-button
            >
            <el-button
              type="success"
              size="small"
              v-if="
                vaildData(permission.manage_company_talentsList_upload, false)
              "
              icon="el-icon-upload2"
              @click="handleImport"
              :disabled="!companyId"
              >批量新增</el-button
            >
            <el-button
              type="danger"
              size="small"
              icon="el-icon-delete"
              v-if="
                vaildData(permission.manage_company_talentsList_delete, false)
              "
              @click="handleDelete"
              :disabled="!companyId"
              >删 除</el-button
            >
          </template>
        </avue-crud>
      </basic-container>
    </el-col>
    <el-dialog
      title="用户数据导入"
      append-to-body
      :visible.sync="excelBox"
      width="555px"
    >
      <avue-form
        :option="excelOption"
        v-model="excelForm"
        :upload-after="uploadAfter"
        :upload-before="beforeAvatarUpload"
        :upload-error="uploadError"
      >
        <template slot="excelTemplate">
          <el-button
            type="primary"
            @click="handleTemplate()"
            :loading="templateLoading"
          >
            点击下载
            <i class="el-icon-download el-icon--right"></i>
          </el-button>
        </template>
      </avue-form>
    </el-dialog>
    <ied ref="ied"></ied>
  </el-row>
</template>


<script>
import {
  getList,
  detail,
  save,
  update,
  remove,
  importTalents,
} from "@/api/manage/talents";
import { mapGetters } from "vuex";
import {
  isvalidatemobile,
  validatename,
  validatenull,
  isExcel,
  check18IdCardNo,
} from "@/util/validate";
import companyTree from "./companyTree";
import { getWorkTypes } from "@/api/manage/worktypes";
import { getTemplate } from "@/api/resource/template";
import ied from "@/views/util/import-error-dialog";
import { excelAccept } from "@/common/accept";

export default {
  components: { companyTree, ied },
  name: "manage_company_talentsList",
  data() {
    return {
      companyId: null,
      loading: false,
      templateLoading: false,
      excelBox: false,
      selectionList: [],
      data: [],
      form: {},
      query: {},
      worktypes: [],
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 10,
      },
      excelForm: {},
    };
  },
  created() {},
  methods: {
    nodeClick({ data }) {
      this.companyId = data.id;
      this.$refs.crud.searchReset();
      this.page.currentPage = 1;
      this.refreshChange();
      this.updateWorkTypes(data.id);
    },
    updateWorkTypes(id) {
      if (id) {
        getWorkTypes(id).then((res) => {
          this.worktypes = res.data.data;
        });
      }
    },
    rowSave(row, done) {
      const data = {
        companyId: this.companyId,
        idNumber: row.idNumber,
        name: row.name,
        telphone: row.telphone,
        worktypes: row.worktypes.join(","),
      };
        save(data).then(
        () => {
          this.onLoad(this.page, this.query);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          window.console.log(error);
          done();
        }
      );
    
    },
    rowUpdate(row, index, done, loading) {
      const data = {
        id: row.id,
        companyId: this.companyId,
        idNumber: row.idNumber,
        name: row.name,
        telphone: row.telphone,
        worktypes: row.worktypes,
      };
      update(data).then(
        () => {
          this.onLoad(this.page, this.query);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          window.console.log(error);
          loading();
        }
      );
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page, this.query);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        });
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page, this.query);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    beforeOpen(done, type) {
      if (["add", "edit"].includes(type)) {
        done();
      }
      if (["edit", "view"].includes(type)) {
        detail(this.form.id).then((resp) => {
          resp.data.data.worktypes = resp.data.data.worktypes.split(",");
          this.form = resp.data.data;
          done();
        });
      }
    },
    beforeClose(done) {
      done();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      if (this.companyId) {
        this.loading = true;
        params;
        getList(
          page.currentPage,
          page.pageSize,
          Object.assign(this.query, params),
          this.companyId
        ).then((res) => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
        });
      }
    },
    uploadAfter(res, done) {
      if (!(res instanceof Error) && !res.data) {
        this.excelBox = false;
      } else if (res.data && res.data.code === 900) {
        const arr = [];
        const data = res.data.data;
        data.error &&
          data.error.errorList.forEach((item) => {
            arr.push(`${item.name} ${item.remarks}`);
          });
        data.auth &&
          data.auth.authList.forEach((item) => {
            arr.push(`${item.name} ${item.remarks}`);
          });
        this.$refs.ied.show(arr);
      }
      this.refreshChange();
      done();
    },
    uploadError(error) {
      if (error) {
        this.$message.error(error);
      }
    },
    beforeAvatarUpload(file, done, loading) {
      if (!isExcel(file)) {
        loading();
        this.$message.error("上传参保信息只能是 .xls,.xlsx 标准格式文件!");
      } else {
        done();
      }
    },
    handleAdd() {
      this.$refs.crud.rowAdd();
    },
    handleImport() {
      this.excelBox = true;
    },
    handleTemplate() {
      this.templateLoading = true;
      getTemplate("mrc")
        .then((rep) => {
          this.templateLoading = false;
          window.open(rep.data.data);
        })
        .catch(() => {
          this.templateLoading = false;
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message({ type: "warning", message: "请至少选择一条" });
        return;
      } else {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.loading = true;
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page, this.query);
            this.$message({
              type: "success",
              message: "操作成功!",
            });
          });
      }
    },
  },
  computed: {
    ...mapGetters(["userInfo", "permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(
          this.permission.manage_company_talentsList_add,
          false
        ),
        viewBtn: this.vaildData(
          this.permission.manage_company_talentsList_view,
          false
        ),
        editBtn: this.vaildData(
          this.permission.manage_company_talentsList_edit,
          false
        ),
        delBtn: this.vaildData(
          this.permission.manage_company_talentsList_delete,
          false
        ),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
    excelOption() {
      return {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: "文件上传",
            prop: "excelFile",
            type: "upload",
            drag: true,
            loadText: "文件上传中，请稍等",
            span: 24,
            propsHttp: {
              res: "data",
            },
            tip: "请上传 .xls,.xlsx 标准格式文件",
            accept: excelAccept,
            showFileList: false,
            action: importTalents(this.companyId, this.excelForm.isCovered),
          },
          {
            label: "数据覆盖",
            prop: "isCovered",
            type: "switch",
            align: "center",
            width: 80,
            dicData: [
              {
                label: "否",
                value: 0,
              },
              {
                label: "是",
                value: 1,
              },
            ],
            value: 0,
            slot: true,
            rules: [
              {
                required: true,
                message: "请选择是否覆盖",
                trigger: "blur",
              },
            ],
          },
          {
            label: "模板下载",
            prop: "excelTemplate",
            formslot: true,
            span: 24,
          },
        ],
      };
    },
    option() {
      return {
        height: "auto",
        calcHeight: 186,
        tip: false,
        page: true,
        addBtn: false,
        delBtn: false,
        viewBtn: true,
        editBtn: true,
        selection: true,
        searchShow: true,
        searchMenuSpan: 6,
        dialogType: "drawer",
        labelWidth: 95,
        border:true,
        column: [
          {
            type: "input",
            label: "姓名",
            span: 12,
            display: true,
            size: "small",
            prop: "name",
            search: true,
            searchSpan: 4,
            searchLabelWidth: 50,
            rules: [
              {
                required: true,
                whitespace: true,
                validator(rule, value, callback) {
                  if (value === "") {
                    callback(new Error("请输入姓名"));
                  } else if (validatename(value)) {
                    callback();
                  } else {
                    callback(new Error("姓名格式不正确"));
                  }
                },
                trigger: "blur",
              },
            ],
            placeholder: "姓名",
          },
          {
            type: "input",
            label: "身份证号码",
            span: 12,
            display: true,
            size: "small",
            prop: "idNumber",
            search: true,
            searchLabelWidth: 89,
            rules: [
              {
                required: true,
                whitespace: true,
                message: "请输入身份证号",
              },
              {
                validator(rule, value, callback) {
                  if (check18IdCardNo(value)) {
                    callback();
                  } else {
                    callback(new Error("身份证格式不正确"));
                  }
                },
                trigger: "blur",
              },
            ],
            placeholder: " 身份证号",
          },
          {
            label: "工种",
            prop: "worktypes",
            type: "select",
            multiple: true,
            span: 12,
            dicData: this.worktypes,
            props: { label: "name", value: "name" },
            rules: [
              {
                required: true,
                message: "请选择工种",
              },
            ],
          },
          {
            type: "input",
            label: "手机号码",
            span: 12,
            display: true,
            size: "small",
            prop: "telphone",
            rules: [
              /*{
                required: true,
                whitespace: true,
                message: "请输入手机号码",
              },*/
              {
                validator(rule, value, callback) {
                  if (validatenull(value)) {
                    callback();
                    return;
                  }
                  let list = isvalidatemobile(value);
                  if (list[0]) {
                    callback(new Error(list[1]));
                  } else {
                    callback();
                  }
                },
                trigger: "blur",
              },
            ],
            placeholder: "手机号",
          },
        ],
      };
    },
  },
};
</script>

<style>
</style>