<template>
  <el-container>
    <el-header v-if="isSearch">
      <el-form style="margin: 10px 0" :inline="true">
        <el-form-item label="单位名称：">
          <el-input
            v-model="search.companyName"
            placeholder="请输入单位名称"
            maxlength="30"
            clearable
          />
        </el-form-item>
        <el-form-item label="姓名：">
          <el-input
            v-model="search.compellation"
            placeholder="请输入姓名"
            maxlength="30"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button
            style="margin-left: 10px"
            type="primary"
            icon="el-icon-search"
            @click="getList"
          >
            搜索
          </el-button>
          <el-button class="commonBtn" icon="el-icon-refresh" @click="reset">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-header>
    <el-main>
      <div class="headerTop">
        <div>
          <el-button
            type="primary"
            class="el-icon-plus"
            @click="handleItem('add')"
          >
            新增</el-button
          >
          <el-button
            icon="el-icon-delete"
            type="primary"
            :disabled="multipleSelection.length < 1"
            @click="dleSignTemolate"
            >删除</el-button
          >
          <!-- <el-button
            type="primary"
            class="el-icon-download"
            @click="handleExport"
          >
            导出文档</el-button
          > -->
        </div>
        <right-toolbar
          :showSearch.sync="isSearch"
          @queryTable="reset"
        ></right-toolbar>
      </div>
      <el-table
        height="calc(100% - 200px)"
        :data="list"
        :row-style="{ height: '0px' }"
        :header-cell-style="{ 'text-align': 'center', padding: '0px' }"
        :cell-style="{ 'text-align': 'center', padding: '2px' }"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" align="center" width="50px" />
        <el-table-column label="序号" align="center" width="80px">
          <template slot-scope="scope">
            <span> {{ (pageNum - 1) * pageSize + (scope.$index + 1) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="单位名称" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.companyName || "-" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="姓名" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.compellation || "-" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="性别" align="center">
          <template slot-scope="scope">
            <span>{{ sex_type[scope.row.sex] || "-" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="学历" align="center">
          <template slot-scope="scope">
            <span>{{ educationType[scope.row.education] || "-" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="身份证号" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.idNumber || "-" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="用户名" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.userName || "-" }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="是否可登录app" align="center">
          <template slot-scope="scope">
            <span>{{ login_app_type[scope.row.loginApp] || "-" }}</span>
          </template>
        </el-table-column> -->
        <el-table-column label="操作" align="center" width="300">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="mini"
              @click="handleItem('edit', scope.row)"
            >
              编辑
            </el-button>
            <el-button
              type="text"
              size="mini"
              @click="handleItem('check', scope.row)"
            >
              查看
            </el-button>
            <!-- <el-button
              type="text"
              size="mini"
              @click="handlePassword(scope.row)"
            >
              重置密码
            </el-button> -->
            <el-button
              type="text"
              size="mini"
              @click="dleSignTemolate(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :page.sync="pageNum"
        :limit.sync="pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :total="total"
        @pagination="getList"
      />
    </el-main>
    <el-dialog
      :visible.sync="addAlert"
      width="60%"
      :title="title"
      :show-close="false"
    >
      <el-form
        ref="formData"
        :model="formData"
        label-position="right"
        :rules="rules1"
        style="padding: 0 20px; height: 700px; overflow: auto"
        label-width="160px"
        :disabled="isCheck"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="单位名称：" prop="contractorId">
              <el-select
                style="width: 90%"
                v-model="formData.contractorId"
                clearable
                size="medium"
                @change="handleProfession"
              >
                <el-option
                  v-for="item in contractorList"
                  :key="item.id"
                  :label="item.companyName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名：" prop="compellation">
              <el-input
                style="width: 90%"
                v-model="formData.compellation"
                maxlength="30"
                placeholder="请输入姓名"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="type === 'add'">
          <el-col :span="12">
            <el-form-item label="用户名：" prop="userName">
              <el-input
                style="width: 90%"
                v-model="formData.userName"
                maxlength="30"
                placeholder="请输入用户名"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码：" prop="password">
              <el-input
                style="width: 90%"
                v-model="formData.password"
                maxlength="18"
                placeholder="请输入密码"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="性别：" prop="sex">
              <el-select
                style="width: 90%"
                v-model="formData.sex"
                size="medium"
                clearable
              >
                <el-option
                  v-for="item in sexType"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学历：" prop="education">
              <el-select
                style="width: 90%"
                v-model="formData.education"
                size="medium"
                clearable
              >
                <el-option
                  v-for="item in ticketType"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="身份证号：" prop="idNumber">
              <el-input
                style="width: 90%"
                v-model="formData.idNumber"
                maxlength="18"
                placeholder="请输入身份证号"
                clearable
              />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="是否可登录app：" prop="loginApp">
              <el-select
                style="width: 90%"
                v-model="formData.loginApp"
                size="medium"
                clearable
              >
                <el-option
                  v-for="item in loginAppType"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
          </el-col> -->
        </el-row>
        <el-form-item label="工种列表：">
          <div
            v-for="(edit, index) in formData.contractorProfessionList"
            :key="index"
            class="form-list"
          >
            <div class="form-item">
              <el-row style="margin-bottom: 20px">
                <el-col :span="12">
                  <el-form-item
                    label="工种："
                    :prop="homeCheck(index)"
                    :rules="[
                      {
                        required: true,
                        message: '请选择工种',
                        trigger: 'change',
                      },
                    ]"
                  >
                    <el-select
                      style="width: 90%"
                      v-model="edit.contractorProfessionId"
                      size="medium"
                      clearable
                      @change="handleDisabled"
                    >
                      <el-option
                        v-for="item in professionList"
                        :key="item.id"
                        :label="item.professionName"
                        :value="item.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="证书编号：">
                    <el-input
                      style="width: 90%"
                      v-model="edit.certificateCode"
                      maxlength="50"
                      placeholder="请输入证书编号"
                      clearable
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row style="margin-bottom: 20px">
                <el-col :span="12">
                  <el-form-item label="证书有效期开始时间：">
                    <el-date-picker
                      style="width: 90%"
                      v-model="edit.certificateStartDate"
                      type="date"
                      placeholder="选择日期"
                      clearable
                    >
                    </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="证书有效期结束时间：">
                    <el-date-picker
                      style="width: 90%"
                      v-model="edit.certificateEndDate"
                      type="date"
                      placeholder="选择日期"
                      clearable
                    >
                    </el-date-picker>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="证书图片：">
                    <ImageUpload
                      v-model="edit.certificateImage"
                      :isShowTip="false"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
            <div class="add_button" v-if="!isCheck">
              <span
                v-if="formData.contractorProfessionList.length !== 1"
                @click="handleDelItmes(index)"
                class="el-icon-remove"
              />
              <span
                v-if="formData.contractorProfessionList.length === index + 1"
                class="el-icon-circle-plus"
                @click="addItem"
              />
            </div>
            <div v-else style="width: 26px"></div>
          </div>
        </el-form-item>
      </el-form>
      <el-row style="margin-top: 10px">
        <el-col align="right">
          <el-button @click="handleClose"> 取消 </el-button>
          <el-button
            :loading="loading"
            type="primary"
            @click="handleSave"
            v-if="!isCheck"
          >
            确定
          </el-button>
        </el-col>
      </el-row>
    </el-dialog>
    <el-dialog
      :visible.sync="isPassword"
      width="400px"
      title="重置密码"
      :show-close="false"
    >
      <el-form ref="form" :model="user" :rules="rules" label-width="80px">
        <el-form-item label="旧密码" prop="oldPassword">
          <el-input
            v-model="user.oldPassword"
            placeholder="请输入旧密码"
            type="password"
            show-password
          />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="user.newPassword"
            placeholder="请输入新密码"
            type="password"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="user.confirmPassword"
            placeholder="请确认新密码"
            type="password"
            show-password
          />
        </el-form-item>
        <el-row style="margin-top: 10px">
          <el-col align="right">
            <el-button @click="close">取消</el-button>
            <el-button type="primary" size="mini" @click="submit"
              >确定</el-button
            >
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
  </el-container>
</template>

<script>
import { dictType } from "@/api/jobSheet.js";
import {
  queryContractorList,
  queryUserList,
  queryProfessionList,
  delUser,
  editUser,
  getUserDetails,
  addUser,
} from "@/api/contractor.js";
export default {
  name: "RuoyiIndex",
  data() {
    const equalToPassword = (rule, value, callback) => {
      if (this.user.newPassword !== value) {
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
      }
    };
    const regPassword = (rule, value, callback) => {
      const reg =
        /^(?![a-zA-z]+$)(?!\d+$)(?![!@#$%^&*.]+$)(?![a-zA-z\d]+$)(?![a-zA-z!@#$%^&*.]+$)(?![\d!@#$%^&*.]+$)[a-zA-Z\d!@#$%^&*.]{6,18}$/;
      if (!reg.test(value)) {
        callback(
          new Error(
            "密码必须包含字母、数字和特殊字符(!@#$%^&*.)，且在6~18位之间"
          )
        );
      } else {
        callback();
      }
    };
    const userNmae = (rule, value, callback) => {
      const reg = /^[a-zA-Z]{1}([a-zA-Z0-9]|[._]){4,19}$/;
      if (!reg.test(value)) {
        callback(
          new Error("只能输入5-20个以字母开头、可带数字、“_”、“.”的字串")
        );
      } else {
        callback();
      }
    };
    return {
      loading: false,
      isPassword: false,
      user: {
        oldPassword: undefined,
        newPassword: undefined,
        confirmPassword: undefined,
      },
      // 表单校验
      rules: {
        oldPassword: [
          { required: true, message: "旧密码不能为空", trigger: "blur" },
        ],
        newPassword: [
          { required: true, message: "新密码不能为空", trigger: "blur" },
          { required: true, validator: regPassword, trigger: "blur" },
        ],
        confirmPassword: [
          { required: true, message: "确认密码不能为空", trigger: "blur" },
          { required: true, validator: equalToPassword, trigger: "blur" },
        ],
      },
      //模糊搜索
      search: {
        companyName: "",
        compellation: "",
      },
      contractorList: [],
      title: "",
      type: "",
      total: 0,
      isSearch: true,
      list: [],
      multipleSelection: [],
      pageNum: 1,
      pageSize: 10,
      addAlert: false,
      isCheck: false,
      rowId: "",
      formData: {
        compellation: "",
        contractorId: "",
        contractorProfessionList: [
          {
            certificateCode: "",
            certificateEndDate: "",
            certificateImage: "",
            certificateStartDate: "",
            contractorProfessionId: "",
          },
        ],
        education: "",
        idNumber: "",
        loginApp: "",
        password: "",
        sex: "",
        userName: "",
      },
      rules1: {
        compellation: [
          { required: true, message: "请输入姓名", trigger: "blur" },
        ],
        userName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { required: true, validator: userNmae, trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { required: true, validator: regPassword, trigger: "blur" },
        ],
        contractorId: [
          { required: true, message: "请输入单位名称", trigger: "blur" },
        ],
        sex: [{ required: true, message: "请选择性别", trigger: "blur" }],
      },
      ticketType: [],
      professionList: [],
      disabledList: [],
      sexType: [
        {
          code: 0,
          name: "女",
        },
        {
          code: 1,
          name: "男",
        },
      ],
      loginAppType: [
        {
          code: 0,
          name: "不可登录",
        },
        {
          code: 1,
          name: "可登录",
        },
      ],
    };
  },
  computed: {
    educationType() {
      return this.ticketType.reduce((t, item) => {
        return {
          ...t,
          [item.dictValue]: item.dictLabel,
        };
      }, {});
    },
    sex_type() {
      return this.sexType.reduce((t, item) => {
        return {
          ...t,
          [item.code]: item.name,
        };
      }, {});
    },
    login_app_type() {
      return this.loginAppType.reduce((t, item) => {
        return {
          ...t,
          [item.code]: item.name,
        };
      }, {});
    },
    homeCheck() {
      return (index) =>
        `contractorProfessionList.${index}.contractorProfessionId`;
    },
  },
  created() {
    this.getTotalList();
  },

  methods: {
    handleDisabled(id) {
      const arr = this.formData.contractorProfessionList.map(
        (item) => item.contractorProfessionId
      ).filter(item => item === id);
      if (arr.length > 1) {
        this.$message({
          message: "同一工种只能添加一次!!!",
          type: "warning",
        });
      }
    },
    handlePassword(row) {
      this.isPassword = true;
      this.passwordId = row.id;
    },
    submit() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          // updateUserPwd(this.user.oldPassword, this.user.newPassword).then(
          //   (response) => {
          //     this.$modal.msgSuccess("修改成功");
          //   }
          // );
        }
      });
    },
    close() {
      this.user = this.$options.data().user;
      this.$refs.form.resetFields();
      this.isPassword = false;
    },
    handleProfession() {
      this.getProfessionList();
      this.formData.contractorProfessionList.forEach((item) => {
        item.contractorProfessionId = "";
      });
    },
    reset() {
      this.search = this.$options.data().search;
      this.getList();
    },
    getTotalList() {
      const params = {
        pageNum: 1,
        pageSize: 100,
      };
      dictType({ ...params, dictType: "sys_education" }).then((data) => {
        if (data.code === 200) {
          this.ticketType = data.rows || [];
        } else {
          this.$message.error(data.msg);
        }
      });
      this.getContractorList();
      this.getList();
    },
    getContractorList() {
      const params = {
        pageNum: 1,
        pageSize: 100,
      };
      queryContractorList(params).then((data) => {
        if (data.code === 200) {
          this.contractorList = data.rows || [];
        } else {
          this.$message.error(data.msg);
        }
      });
    },
    getProfessionList() {
      const params = {
        pageNum: 1,
        pageSize: 100,
        contractorId: this.formData.contractorId,
      };
      queryProfessionList(params).then((data) => {
        if (data.code === 200) {
          this.professionList = data.rows || [];
          this.disabledList = data.rows || [];
        } else {
          this.$message.error(data.msg);
        }
      });
    },
    getList() {
      const params = {
        ...this.search,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
      };
      queryUserList(params).then((data) => {
        if (data.code === 200) {
          this.list = data.rows;
          this.total = data.total;
        } else {
          this.$message.error(data.msg);
        }
      });
    },
    // 全选/反选
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    dleSignTemolate(row) {
      let ids =
        row.id || this.multipleSelection.map((item) => item.id).join(",");
      this.$confirm("是否删除？", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delUser(ids).then((data) => {
            if (data.code === 200) {
              this.$message({
                message: "删除成功",
                type: "success",
              });
              this.getList();
            } else {
              this.$message.error(data.msg);
            }
          });
        })
        .catch(() => {
          // 取消后退出
        });
    },
    // 取消添加
    handleClose() {
      this.addAlert = false;
      setTimeout(() => {
        this.isCheck = false;
        this.formData = this.$options.data().formData;
        this.$refs.formData.resetFields();
      }, 200);
    },
    handleDelItmes(index) {
      this.$confirm("是否删除？", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.formData.contractorProfessionList.splice(index, 1);
        })
        .catch(() => {
          // 取消后退出
        });
    },
    addItem() {
      this.formData.contractorProfessionList.push({
        certificateCode: "",
        certificateEndDate: "",
        certificateImage: "",
        certificateStartDate: "",
        contractorProfessionId: "",
      });
    },
    handleSave() {
      const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
      if (this.formData.idNumber && !reg.test(this.formData.idNumber)) {
        console.log(
          reg.test(this.formData.idNumber),
          "reg.test(this.formData.idNumber)"
        );
        this.$message({
          message: "身份证输入不合法",
          type: "warning",
        });
        return;
      }
      const arr = []
      let num = 0
      this.formData.contractorProfessionList.forEach((item) => {
        if (arr.indexOf(item.contractorProfessionId) < 0) {
          arr.push(item.contractorProfessionId)
        } else {
          num += 1
        }
      })
      if (num > 0) {
        this.$message({
          message: "同一工种只能添加一次!!!",
          type: "warning",
        });
        return
      }
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.loading = true;
          if (this.type === "add") {
            addUser(this.formData)
              .then((data) => {
                if (data.code === 200) {
                  this.$message({
                    message: "新增成功",
                    type: "success",
                  });
                  this.handleClose();
                  this.getList();
                } else {
                  this.$message.error(data.msg);
                }
                this.loading = false;
              })
              .catch(() => {
                this.loading = false;
              });
          } else {
            editUser({ ...this.formData, id: this.rowId })
              .then((data) => {
                if (data.code === 200) {
                  this.$message({
                    message: "编辑成功",
                    type: "success",
                  });
                  this.handleClose();
                  this.getList();
                } else {
                  this.$message.error(data.msg);
                }
                this.loading = false;
              })
              .catch(() => {
                this.loading = false;
              });
          }
        } else {
          return false;
        }
      });
    },
    getDetails(id) {
      getUserDetails(id).then((data) => {
        if (data.code === 200) {
          this.formData = data.data;
          this.getProfessionList();
        } else {
          this.$message.error(data.msg);
        }
      });
    },
    handleItem(type, row = {}) {
      this.addAlert = true;
      this.type = type;
      this.rowId = row.id;
      if (type === "add") {
        this.title = "新增";
      } else if (type === "edit") {
        this.title = "编辑";
        this.getDetails(row.id);
      } else if (type === "check") {
        this.title = "查看";
        this.isCheck = true;
        this.getDetails(row.id);
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "/doubledefense/user/export",
        {},
        `job_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>

<style lang="scss" scoped>
.form-list {
  display: flex;
  .form-item {
    flex: 1;
    border: solid 1px;
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 10px;
  }
  .add_button {
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    margin-left: 10px;
    margin-bottom: 10px;
    .el-icon-circle-plus {
      font-size: 26px;
      color: #67c23a;
      cursor: pointer;
    }
    .el-icon-remove {
      font-size: 26px;
      color: #f56c6c;
      cursor: pointer;
    }
  }
}
</style>
