<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="unitName">
        <el-input
          v-model="queryParams.unitName"
          maxlength="60"
          show-word-limit
          placeholder="请输入监理单位名称"
          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="unitName" />
      <el-table-column label="单位地址" show-overflow-tooltip align="center" prop="unitAddress" />
      <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">
        <template v-slot="scope">
          <div style="color: #409eff; cursor: pointer" @click="onHandleDirector(scope.row)">
            {{ scope.row.userNum }}
          </div>
        </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="supervisorFormOpen" width="30%" :close-on-click-modal="false">
      <el-form ref="unitForm" :model="unitForm" :rules="unitRules" size="medium" label-width="100px">
        <el-form-item label="监理单位名称" prop="unitName" label-width="140px">
          <el-input
            v-model="unitForm.unitName"
            placeholder="请输入监理单位名称"
            show-word-limit
            :maxlength="60"
            @blur="checkIsExistUnitName"
            clearable
            v-no-whitespace
            :style="{ width: '100%' }"
            :disabled="view"
          ></el-input>
        </el-form-item>
        <el-form-item label="监理单位地址" prop="unitAddress" label-width="140px">
          <el-input
            v-model="unitForm.unitAddress"
            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="unitForm.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="unitForm.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="unitForm.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="directorsName" label-width="140px">-->
        <!--          <el-input v-model="unitForm.directorsName" 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="directorsPhone" label-width="140px">-->
        <!--          <el-input v-model="unitForm.directorsPhone" 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="unitForm.supId == undefined" label="总监身份证" prop="directorsIdCard" label-width="140px">-->
        <!--          <el-input v-model="unitForm.directorsIdCard" 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>

    <!-- 列表二级弹框 -->
    <el-dialog
      title="总监列表"
      :visible.sync="directorOuterVisible"
      width="60%"
      :close-on-click-modal="false"
      append-to-body
    >
      <!-- 查询 -->
      <el-form :model="directorQueryParams" ref="queryForm" size="small" inline>
        <el-form-item prop="directorsName">
          <el-input
            clearable
            placeholder="请输入姓名"
            v-model="directorQueryParams.directorsName"
            @keyup.enter.native="onHandleQueryDirectorList"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="onHandleQueryDirectorList">
            查询
          </el-button>
          <el-button icon="el-icon-plus" size="mini" @click="onHandleAddDirector">新增</el-button>
        </el-form-item>
      </el-form>

      <!-- 列表 -->
      <el-table :data="directorList">
        <el-table-column
          type="index"
          width="55"
          label="序号"
          align="center"
          :index="indexContinuous(directorQueryParams.pageNum, directorQueryParams.pageSize)"
        />
        <el-table-column label="姓名" prop="directorsName" show-overflow-tooltip align="center" />
        <el-table-column label="联系电话" prop="directorsPhone" show-overflow-tooltip align="center" />
        <el-table-column label="身份证号码" prop="commUserCode" show-overflow-tooltip align="center" />
        <el-table-column label="操作" align="center">
          <template slot-scope="{ row }">
            <el-button size="mini" type="primary" plain @click="onHandleEdit(row)">编辑</el-button>
            <el-button v-if="row.status == 0" size="mini" type="danger" plain @click="onHandleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        :total="directorTotal"
        @pagination="onHandleQueryDirectorList"
        :page.sync="directorQueryParams.pageNum"
        :limit.sync="directorQueryParams.pageSize"
      />

      <!-- 内层弹框 -->
      <el-dialog
        width="40%"
        append-to-body
        :before-close="onHandleCancel"
        :title="`${directorInnerTitle}总监`"
        :visible.sync="directorInnerVisible"
      >
        <el-form
          size="small"
          label-width="120px"
          :model="directorAddForm"
          ref="directorAddFormRef"
          :rules="directorAddFormRules"
        >
          <el-form-item prop="directorsName" label="总监">
            <el-input placeholder="请输入" v-model="directorAddForm.directorsName" clearable />
          </el-form-item>
          <el-form-item prop="directorsIdCard" label="总监身份证">
            <el-input
              clearable
              placeholder="请输入"
              v-model="directorAddForm.directorsIdCard"
              :disabled="directorInnerTitle === '编辑'"
            />
          </el-form-item>
          <el-form-item prop="directorsPhone" label="总监联系方式">
            <el-input
              clearable
              placeholder="请输入"
              v-model="directorAddForm.directorsPhone"
              :disabled="directorInnerTitle === '编辑'"
            />
          </el-form-item>
        </el-form>

        <el-row style="text-align: right">
          <el-button size="mini" @click="onHandleCancel">取消</el-button>
          <el-button type="primary" size="mini" @click="onHandleSubmit">确定</el-button>
        </el-row>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script>
import { addSupervisoryUnit, addSupervisoryUnitUser, checkIsExistUnitName } from '@/api/pro/proList'
import {
  delSupervisionUnit,
  listSupervisionUnit,
  updateSupervisionUnit,
  getDirectorListApi,
  addDirectorInfoApi,
  editDirectorInfoApi,
  deleteDirectorInfoApi,
} from '@/api/externalUnitManagement/supervisionUnit'
import numberUtils from '@/utils/validate'
import { hideSensitiveInfo } from '../../../utils/bonus'

export default {
  name: 'Post',
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      postList: [{ directorsName: 9 }, { directorsName: 9 }, { directorsName: 10 }],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      supervisorFormOpen: false,
      edit: false,
      view: false,
      // 是否显示提交按键
      showOrNot: true,
      // 地图是否显示弹出层
      innerVisible: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        unitName: undefined,
      },
      // 表单参数
      unitForm: {
        supId: undefined,
      },
      //监理单位form表单 校验
      unitRules: {
        unitName: [
          {
            required: true,
            message: '请输入监理单位名称',
            trigger: 'blur',
          },
        ],
        unitAddress: [
          {
            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',
          },
        ],
        directorsName: [
          {
            required: true,
            message: '请输入总监姓名',
            trigger: 'blur',
          },
        ],
        directorsPhone: [
          {
            required: true,
            validator: numberUtils.checkPhone,
            trigger: 'blur',
          },
        ],
        directorsIdCard: [
          {
            required: true,
            validator: numberUtils.checkIdCardNumber,
            trigger: 'blur',
          },
        ],
      },

      // 总监弹框(外层)
      directorOuterVisible: false,
      // 总监弹框(内层)
      directorInnerVisible: false,
      // 内层弹框标题
      directorInnerTitle: '新增',
      // 查询参数
      directorQueryParams: {
        unitId: '',
        directorsName: '', // 姓名
        pageNum: 1,
        pageSize: 20,
      },
      // 列表数据源
      directorList: [],
      // 列表条数
      directorTotal: 0,
      // 新增总监参数
      directorAddForm: {
        directorsName: '',
        directorsPhone: '',
        directorsIdCard: '',
        commUserId: '',
        supId: '',
        jlId: '',
      },
      // 新增总监 rules
      directorAddFormRules: {
        directorsName: [
          {
            required: true,
            message: '请输入总监姓名',
            trigger: 'blur',
          },
        ],
        directorsPhone: [
          {
            required: true,
            message: '请输入总监联系方式',
            trigger: 'blur',
          },
          // 手机号码正则
          {
            pattern: /^1[3456789]\d{9}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur',
          },
        ],
        directorsIdCard: [
          {
            required: true,
            message: '请输入身份证号码',
            trigger: 'blur',
          },
          // 手机号码正则
          {
            // 身份证号码的正则表达式
            pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
            message: '请输入正确的身份证号码',
            trigger: 'blur',
          },
        ],
      },
    }
  },
  created() {
    this.getList()
  },
  methods: {
    hideSensitiveInfo,

    /** 查询设备列表 */
    getList() {
      this.loading = true
      listSupervisionUnit(this.queryParams).then(response => {
        this.postList = response.rows
        console.log('postList:', this.postList)
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.supervisorFormOpen = false
      this.unitResetForm()
    },
    openUserInfo() {
      this.directorOuterVisible = true
    },
    // 表单重置
    reset() {
      this.form = {
        unitName: undefined,
      }
      this.resetForm('form')
    },
    //监理单位表单重置
    unitResetForm() {
      this.unitForm = {
        supId: undefined,
        unitName: undefined,
        unitAddress: undefined,
        corporateName: undefined,
        corporatePhone: undefined,
        socialUnifiedCreditCode: undefined,
        directorsName: undefined,
        directorsPhone: undefined,
      }
      this.resetForm('unitForm')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.supId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      //创建监理单位
      this.unitResetForm()
      this.edit = false
      this.view = false
      this.supervisorFormOpen = true
      this.showOrNot = true
      this.title = '添加监理单位'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.handleQuery()
      this.unitResetForm()
      this.unitForm = row
      this.edit = true
      this.view = false
      this.supervisorFormOpen = true
      this.showOrNot = true
      this.title = '修改监理单位'
    },

    /** 查看按钮操作 */
    handleView(row) {
      this.handleQuery()
      this.unitResetForm()
      this.unitForm = row
      this.edit = true
      this.view = true
      this.showOrNot = false
      this.supervisorFormOpen = true
      this.title = '查看监理单位'
    },

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

    //检查单位名称是否存在
    async checkIsExistUnitName() {
      const params = {
        unitName: this.unitForm.unitName,
        supId: this.unitForm.supId,
      }
      try {
        const response = await checkIsExistUnitName(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.supId || this.ids
      this.$modal
        .confirm('是否确认删除工程编号为"' + addressIds + '"的数据项？')
        .then(function () {
          return delSupervisionUnit(addressIds)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.derive(
        'project/SupervisionUnit/export',
        {
          ...this.queryParams,
        },
        `监理单位_${new Date().getTime()}.xlsx`
      )
    },

    // 点击列表总监数量时打开弹框
    onHandleDirector(row) {
      console.log('row当前行信息', row)
      this.directorQueryParams.unitId = row.supId
      this.onHandleQueryDirectorList()
      this.directorOuterVisible = true
    },
    // 查询弹框内总监列表
    async onHandleQueryDirectorList() {
      const res = await getDirectorListApi(this.directorQueryParams)
      this.directorList = res.rows
      this.directorTotal = res.total
      console.log('总监数据列表', res)
    },
    // 新增总监按钮
    onHandleAddDirector() {
      this.directorInnerTitle = '新增'
      this.directorAddForm.directorsName = ''
      this.directorAddForm.directorsPhone = ''
      this.directorAddForm.directorsIdCard = ''
      this.directorInnerVisible = true
    },
    // 列表编辑按钮
    onHandleEdit(row) {
      this.directorInnerTitle = '编辑'
      this.directorAddForm.directorsName = row.directorsName
      this.directorAddForm.directorsPhone = row.directorsPhone
      this.directorAddForm.directorsIdCard = row.commUserCode
      this.directorAddForm.commUserId = row.commUserId
      this.directorAddForm.supId = row.supId
      this.directorInnerVisible = true
      console.log('row当前行信息', row)
    },
    // 列表删除按钮
    onHandleDelete(row) {
      console.log('row当前行信息', row)
      this.$modal
        .confirm('是否确认删除当前数据？')
        .then(async () => {
          console.log('确认删除--')
          const res = await deleteDirectorInfoApi(row.supId)
          if (res.code === 200) {
            this.$modal.msgSuccess('删除成功')
            this.onHandleQueryDirectorList()
          }
        })

        .catch(() => {})
    },
    // 内层弹框取消按钮
    onHandleCancel() {
      this.$refs.directorAddFormRef.resetFields() // 清除表单校验等问题
      this.directorInnerVisible = false
    },
    // 内层弹框确定按钮
    onHandleSubmit() {
      this.$refs.directorAddFormRef.validate(async valid => {
        if (valid) {
          // 校验通过
          console.log('this.directorAddForm新增总监提交参数', this.directorAddForm)
          this.directorAddForm.jlId = this.directorQueryParams.unitId
          // 根据弹框标题判断当前是新增还是修改
          const SEND_API = this.directorInnerTitle === '新增' ? addDirectorInfoApi : editDirectorInfoApi
          const res = await SEND_API(this.directorAddForm)
          if (res.code === 200) {
            this.$modal.msgSuccess(`${this.directorInnerTitle}成功`)
            this.onHandleQueryDirectorList()
            this.directorInnerVisible = false
          }
        }
      })
    },
  },
}
</script>
