<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.manageName" placeholder="请输入姓名" maxlength="30" clearable/>
        </el-form-item>
        <el-form-item label="承包商类型：">
          <el-select v-model="search.contractorType" 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-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" width="100px" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{ scope.row.companyName || "-" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="负责人姓名" align="center" width="100px">
          <template slot-scope="scope">
            <span>{{ scope.row.manageName || "-" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="负责人电话" align="center" width="120px">
          <template slot-scope="scope">
            <span>{{ scope.row.managePhone || "-" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="通信地址" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{ scope.row.postalAddress || "-" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="承包商类型" align="center" show-overflow-tooltip width="100px">
          <template slot-scope="scope">
            <span>{{ manageName[scope.row.contractorType] || "-" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="安全许可编号" align="center" width="150px" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{ scope.row.securityClearanceCode || "-" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="税码/社会信用代码" align="center" width="200px" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{ scope.row.socialCreditCode || "-" }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="安全许可证证书图片"
          align="center"
          width="150px"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              size="mini"
              @click="handleCheckImg(scope.row.securityClearanceImage)"
            >
              查看
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="营业执照证书图片" align="center" width="150px">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="mini"
              @click="handleCheckImg(scope.row.businessLicenseImage)"
            >
              查看
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="业务资质证书图片" align="center" width="150px">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="mini"
              @click="handleCheckImg(scope.row.businessQualification)"
            >
              查看
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="150" fixed="right">
          <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="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="55%"
      :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="165px"
        :disabled="isCheck"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="单位名称：" prop="companyName">
              <el-input
                style="width: 90%"
                v-model="formData.companyName"
                maxlength="50"
                placeholder="请输入单位名称"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人姓名：" prop="manageName">
              <el-input
                style="width: 90%"
                v-model="formData.manageName"
                maxlength="30"
                placeholder="请输入负责人姓名"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="负责人手机号：" prop="managePhone">
              <el-input
                style="width: 90%"
                v-model="formData.managePhone"
                maxlength="11"
                placeholder="请输入负责人手机号"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="通信地址：" prop="postalAddress">
              <el-input
                style="width: 90%"
                v-model="formData.postalAddress"
                maxlength="50"
                placeholder="请输入通信地址"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="承包商类型：" prop="contractorType">
              <el-select
                style="width: 90%"
                v-model="formData.contractorType"
                size="medium"
              >
                <el-option
                  v-for="item in ticketType"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="税码/社会信用代码：" prop="socialCreditCode">
              <el-input
                style="width: 90%"
                v-model="formData.socialCreditCode"
                maxlength="50"
                placeholder="请输入税码/社会信用代码"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="安全许可编号：" prop="securityClearanceCode">
              <el-input
                style="width: 90%"
                v-model="formData.securityClearanceCode"
                maxlength="50"
                placeholder="请输入安全许可编号"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item
              label="安全许可证证书图片："
              prop="securityClearanceImage"
            >
              <ImageUpload
                v-model="formData.securityClearanceImage"
                :isShowTip="false"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item
              label="营业执照证书图片："
              prop="businessLicenseImage"
            >
              <ImageUpload
                v-model="formData.businessLicenseImage"
                :isShowTip="false"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item
              label="业务资质证书图片："
              prop="businessQualification"
            >
              <ImageUpload
                v-model="formData.businessQualification"
                :isShowTip="false"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </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="imgDialog" width="600px" title="证书图片">
      <div style="padding: 0 20px; height: 500px; overflow: auto">
        <div
          style="height: 500px; margin-bottom: 20px"
          v-for="(item, index) in imgList"
          :key="index"
        >
          <el-image
            style="width: 100%; height: 100%"
            :src="item"
            fit="cover"
            :preview-src-list="imgList"
          >
          </el-image>
        </div>
      </div>
    </el-dialog>
  </el-container>
</template>

<script>
import { dictType } from "@/api/jobSheet.js";
import {
  queryContractorList,
  delContractor,
  editContractor,
  getContractorDetails,
  addContractor,
} from "@/api/contractor.js";
export default {
  name: "RuoyiIndex",

  data() {
    const regex = /^1[3456789]\d{9}$/;
    const validatePhone = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入负责人手机号"));
      } else if (!regex.test(value)) {
        callback(new Error("请输入正确的手机格式"));
      } else {
        callback();
      }
    };
    return {
      loading: false,
      imgDialog: false,
      //模糊搜索
      search: {
        companyName: "",
        manageName: "",
        contractorType: "",
      },
      imgList: [],
      title: "",
      type: "",
      total: 0,
      isSearch: true,
      list: [],
      multipleSelection: [],
      pageNum: 1,
      pageSize: 10,
      addAlert: false,
      isCheck: false,
      rowId: "",
      formData: {
        businessLicenseImage: "",
        businessQualification: "",
        companyName: "",
        contractorType: "",
        manageName: "",
        managePhone: "",
        postalAddress: "",
        securityClearanceCode: "",
        securityClearanceImage: "",
        socialCreditCode: "",
      },
      rules1: {
        companyName: [
          { required: true, message: "请输入单位名称", trigger: "blur" },
        ],
        manageName: [
          { required: true, message: "请输入负责人姓名", trigger: "blur" },
        ],
        managePhone: [
          { required: true, validator: validatePhone, trigger: "blur" },
        ],
        postalAddress: [
          { required: true, message: "请输入通信地址", trigger: "blur" },
        ],
        contractorType: [
          { required: true, message: "请选择承包商类型", trigger: "blur" },
        ],
        socialCreditCode: [
          {
            required: true,
            message: "请输入税码/社会信用代码",
            trigger: "blur",
          },
        ],
        securityClearanceCode: [
          { required: true, message: "请输入安全许可编号", trigger: "blur" },
        ],
        securityClearanceImage: [
          {
            required: true,
            message: "请上传安全许可证证书图片",
            trigger: "blur",
          },
        ],
        businessLicenseImage: [
          {
            required: true,
            message: "请上传营业执照证书图片",
            trigger: "blur",
          },
        ],
        businessQualification: [
          {
            required: true,
            message: "请上传业务资质证书图片",
            trigger: "blur",
          },
        ],
      },
      ticketType: [],
    };
  },
  computed: {
    manageName() {
      return this.ticketType.reduce((t, item) => {
        return {
          ...t,
          [item.dictValue]: item.dictLabel,
        };
      }, {});
    },
  },
  created() {
    this.getTotalList();
  },
  methods: {
    reset() {
      this.search = this.$options.data().search;
      this.getList();
    },
    getTotalList() {
      const params = {
        pageNum: 1,
        pageSize: 100,
      };
      dictType({ ...params, dictType: "sys_contractor_type" }).then((data) => {
        if (data.code === 200) {
          this.ticketType = data.rows;
        } else {
          this.$message.error(data.msg);
        }
      });
      this.getList();
    },
    getList() {
      const params = {
        ...this.search,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
      };
      queryContractorList(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(() => {
          delContractor(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.rowId = "";
        this.isCheck = false;
        this.formData = this.$options.data().formData;
        this.$refs.formData.resetFields();
      }, 200);
    },
    handleSave() {
      console.log(this.formData, "this.imgList");
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.loading = true;
          if (this.type === "add") {
            addContractor(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 {
            editContractor({ ...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) {
      getContractorDetails(id).then((data) => {
        if (data.code === 200) {
          this.formData = data.data;
        } 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/contractor/export",
        {},
        `job_${new Date().getTime()}.xlsx`
      );
    },
    handleCheckImg(imgList) {
      this.imgList = [];
      if (imgList) {
        this.imgDialog = true;
        this.imgList = imgList.split(",").map((item) => {
          return process.env.VUE_APP_BASE_API + item;
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped></style>
