<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="承包商" prop="consName">
        <el-input
          v-model="queryParams.consName"
          placeholder="请输入承包商名称"
          maxlength="60"
          show-word-limit
          clearable v-no-whitespace
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:post:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:post:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="postList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column
        type="index"
        width="55"
        label="序号"
        align="center"
        :index="indexContinuous(queryParams.pageNum, queryParams.pageSize)"
      />
      <el-table-column label="承包商名称" show-overflow-tooltip align="center" prop="consName"/>
      <el-table-column label="单位地址" show-overflow-tooltip align="center" prop="consAddress"/>
      <el-table-column label="法人姓名" align="center" prop="corporateName"/>
      <el-table-column label="法人联系方式" width="120" align="center">
        <template slot-scope="scope">
          <!-- 检查是否存在身份证号 -->
          <span v-if="scope.row.corporatePhone">{{ hideSensitiveInfo(scope.row.corporatePhone) }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="社会统一征信代码" show-overflow-tooltip align="center" prop="socialUnifiedCreditCode"/>
      <el-table-column label="承包商负责人" align="center" prop="contractorPrincipal"/>
      <el-table-column label="承包商负责人联系方式" width="160" align="center">
        <template slot-scope="scope">
          <!-- 检查是否存在身份证号 -->
          <span v-if="scope.row.contractorPrincipalPhone">{{ hideSensitiveInfo(scope.row.contractorPrincipalPhone) }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-order"
            @click="handleView(scope.row)"
            v-hasPermi="['system:post:edit']"
          >查看
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:post:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            v-if="scope.row.status == '0'"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:post:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!--   创建承包商单位 -->
    <el-dialog :title="'创建承包商单位'" :visible.sync="consFormOpen" width="30%" :close-on-click-modal="false">
      <el-form ref="consForm" :model="consForm" :rules="consRules" size="medium" label-width="100px">
        <el-form-item label="承包商单位名称" prop="consName" label-width="140px">
          <el-input v-model="consForm.consName" placeholder="请输入承包商单位名称" show-word-limit :maxlength="60"
                    @blur="checkIsExistConsName"
                    clearable v-no-whitespace
                    :style="{width: '100%'}"
                    :disabled="view"></el-input>
        </el-form-item>
        <el-form-item label="单位地址" prop="consAddress" label-width="140px">
          <el-input v-model="consForm.consAddress" placeholder="请输入单位地址" show-word-limit :maxlength="200"
                    clearable v-no-whitespace
                    :style="{width: '100%'}"
                    :disabled="view"></el-input>
        </el-form-item>
        <el-form-item label="法人姓名" prop="corporateName" label-width="140px">
          <el-input v-model="consForm.corporateName" placeholder="请输入法人姓名" show-word-limit :maxlength="20"
                    clearable v-no-whitespace
                    :style="{width: '100%'}"
                    :disabled="view"></el-input>
        </el-form-item>
        <el-form-item label="法人联系方式" prop="corporatePhone" label-width="140px">
          <el-input v-model="consForm.corporatePhone" placeholder="请输入法人联系方式" show-word-limit :maxlength="11"
                    clearable v-no-whitespace
                    :style="{width: '100%'}"
                    :disabled="view"></el-input>
        </el-form-item>
        <el-form-item label="社会统一征信代码" prop="socialUnifiedCreditCode" label-width="140px">
          <el-input v-model="consForm.socialUnifiedCreditCode" placeholder="请输入社会统一征信代码" show-word-limit
                    :maxlength="20" clearable v-no-whitespace
                    :style="{width: '100%'}"
                    :disabled="view"></el-input>
        </el-form-item>
        <el-form-item label="承包商负责人" prop="contractorPrincipal" label-width="140px">
          <el-input v-model="consForm.contractorPrincipal" placeholder="请输入承包商负责人" show-word-limit
                    :maxlength="20" clearable v-no-whitespace
                    :style="{width: '100%'}"
                    :disabled="edit"></el-input>
        </el-form-item>
        <el-form-item label="承包商负责人联系方式" prop="contractorPrincipalPhone" label-width="170px">
          <el-input v-model="consForm.contractorPrincipalPhone" placeholder="请输入承包商负责人联系方式" show-word-limit
                    :maxlength="11" clearable v-no-whitespace
                    :style="{width: '100%'}"
                    :disabled="edit"></el-input>
        </el-form-item>
        <el-form-item v-if="consForm.contId == undefined" label="承包商负责人身份证" prop="contractorPrincipalIdCard" label-width="170px">
          <el-input v-model="consForm.contractorPrincipalIdCard" placeholder="请输入承包商负责人身份证" show-word-limit
                    :maxlength="18" clearable v-no-whitespace
                    :style="{width: '100%'}"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="showOrNot">
        <el-button type="primary" @click="submitForm" v-preventReClick="5000">提 交</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {addConsUnit, addSupervisoryUnit, checkIsExistConsName, checkIsExistUnitName} from "@/api/pro/proList";
import {delContractor, listContractor, updateContractor} from "@/api/externalUnitManagement/contractor";
import numberUtils from "@/utils/validate";
import { hideSensitiveInfo } from '../../../utils/bonus'

export default {
  name: "Post",
  computed: {

  },
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      postList: [],
      // 弹出层标题
      title: "",
      edit: false,
      view: false,
      // 是否显示提交按键
      showOrNot: true,
      // 是否显示创建承包商单位弹出层
      consFormOpen: false,
      // 地图是否显示弹出层
      innerVisible: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        consName: undefined
      },
      // 承包商单位form表单
      consForm: {
        contId: undefined,
      },
      //承包商单位form表单 校验
      consRules: {
        consName: [{
          required: true,
          message: '请输入承包商单位名称',
          trigger: 'blur'
        }],
        consAddress: [{
          required: true,
          message: '请输入单位地址',
          trigger: 'blur'
        }],
        corporateName: [{
          required: true,
          message: '请输入法人姓名',
          trigger: 'blur'
        }],
        corporatePhone: [{
            required: true,
            validator:numberUtils.checkPhone,
            trigger: 'blur'
          }],
        socialUnifiedCreditCode: [{
          required: true,
          message: '请输入社会统一征信代码',
          trigger: 'blur'
        },
          {
            pattern: /^[a-zA-Z0-9]+$/,
            message: '请输入数字或字母',
            trigger: 'blur'
          }],
        contractorPrincipal: [{
          required: true,
          message: '请输入承包商负责人',
          trigger: 'blur'
        }],
        contractorPrincipalPhone: [{
            required: true,
            validator:numberUtils.checkPhone,
            trigger: 'blur'
          }],
        contractorPrincipalIdCard: [{
          required: true,
          validator:numberUtils.checkIdCardNumber,
          trigger: 'blur'
        }]
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    hideSensitiveInfo,

    /** 查询设备列表 */
    getList() {
      this.loading = true;
      listContractor(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.postList = response.rows;
        console.log('postList:', this.postList)
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.consFormOpen = false;
      this.consResetForm();
    },
    // 表单重置
    reset() {
      this.form = {
        consName: undefined
      };
      this.resetForm("queryForm");
    },
    //承包商表单重置
    consResetForm() {
      this.consForm = {
        contId: undefined,
        consName: undefined,
        consAddress: undefined,
        corporateName: undefined,
        corporatePhone: undefined,
        socialUnifiedCreditCode: undefined,
        contractorPrincipal: undefined,
        contractorPrincipalPhone: undefined
      };
      this.resetForm("consForm");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.contId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      //创建监理单位
      this.consResetForm();
      this.consFormOpen = true;
      this.edit = false;
      this.view = false;
      this.showOrNot = true;
      this.title = "添加监理单位";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.handleQuery();
      this.consResetForm();
      this.consForm = row;
      this.consFormOpen = true;
      this.edit = true;
      this.view = false;
      this.showOrNot = true;
      this.title = "修改监理单位";
    },

    /** 查看按钮操作 */
    handleView(row) {
      this.handleQuery();
      this.consResetForm();
      this.consForm = row;
      this.consFormOpen = true;
      this.edit = true;
      this.view = true;
      this.showOrNot = false;
      this.title = "查看工程地址";
    },

    /** 提交按钮 */
    submitForm: function() {
      this.$refs['consForm'].validate(async valid => {
        if (!valid) {
          return false;
        } else {
          // TODO 提交表单
          if (this.consForm.contId !== undefined) {
            updateContractor(this.consForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.consFormOpen = false;
              this.getList();
            });
          }else {
            // 前端验证通过，再进行唯一性检查
            const isExist = await this.checkIsExistConsName();
            if (isExist === false) {
              // 如果单位名称已存在，可以做出相应的提示或处理
              return;
            }
            addConsUnit(this.consForm).then(response => {
              if (response.code === 200) {
                this.$message({
                  message: '新建成功',
                  type: 'success'
                })
                this.consResetForm();
                this.consFormOpen = false;
                this.getList();
              } else {
                this.$message({
                  message: response.msg,
                  type: 'error'
                })
              }
            })
          }

        }
      })
    },

    //检查承包商单位名称是否存在
    async checkIsExistConsName() {
      const params = {
        consName: this.consForm.consName,
        consId: this.consForm.contId
      }
      try {
        const response = await checkIsExistConsName(params)
        if (response.code === 500) {
          this.$message({
            message: response.msg,
            type: 'error'
          });
          // 返回 false 或者其他值，表示单位名称已存在
          return false;
        } else {
          // 返回 true 或者其他值，表示单位名称不存在重复
          return true;
        }
      } catch (error) {
        return false;
      }
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const addressIds = row.contId || this.ids;
      this.$modal.confirm('是否确认删除工程编号为"' + addressIds + '"的数据项？').then(function () {
        return delContractor(addressIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.derive('project/contractor/export', {
        ...this.queryParams
      }, `承包商管理_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
