<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="subName" label-width="120px">
        <el-input
          v-model="queryParams.subName"
          placeholder="请输入分包商名称"
          maxlength="60"
          v-no-whitespace
          show-word-limit
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="proType">
        <el-select v-model="queryParams.status" placeholder="请选择当前状态" clearable>
          <el-option
            v-for="dict in statusDict"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label-width="100px" label="创建时间范围">
        <el-date-picker v-model="createTime" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
                        :editable="false" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
        ></el-date-picker>
      </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:subList:add']"
        >新建
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:subList:export']"
        >导出数据
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="subList" @selection-change="handleSelectionChange">
      <el-table-column
        type="index"
        width="55"
        label="序号"
        align="center"
        :index="indexContinuous(queryParams.pageNum, queryParams.pageSize)"
      />
      <el-table-column label="分包商名称" align="center" prop="subName" />
      <el-table-column label="单位地址" align="center" prop="address" />
      <el-table-column label="法人姓名" align="center" prop="corporateName" />
      <el-table-column label="法人联系方式" 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="社会统一征信代码" align="center" prop="socialUnifiedCreditCode" />
      <el-table-column label="分包商负责人" align="center" prop="subPrincipal" />
      <el-table-column label="分包商负责人联系方式" align="center">
        <template slot-scope="scope">
          <!-- 检查是否存在身份证号 -->
          <span v-if="scope.row.subPrincipalPhone">{{ hideSensitiveInfo(scope.row.subPrincipalPhone) }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="当前状态" align="center" prop="status" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleView(scope.row)"
            v-hasPermi="['system:outsourcingPro:cons']"
          >查看
          </el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleNotice(scope.row)"
            v-if="scope.row.status !== '已入场'"
            v-hasPermi="['system:subList:preparation']"
          >入场通知
          </el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:subList:del']"
          >删除
          </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="subOpen" width="35%" :close-on-click-modal="false">
      <el-form ref="subForm" :model="subForm" :rules="subRules" size="medium" label-width="100px">
        <el-form-item label="分包商单位名称" prop="subName" label-width="180px">
          <el-input v-model="subForm.subName" placeholder="请输入分包商单位名称" show-word-limit :maxlength="60"
                    @blur="checkIsExistSubName"
                    clearable v-no-whitespace
                    :style="{width: '100%'}"
          ></el-input>
        </el-form-item>
        <el-form-item label="单位地址" prop="address" label-width="180px">
          <el-input v-model="subForm.address" placeholder="请输入单位地址" show-word-limit :maxlength="200"
                    clearable v-no-whitespace
                    :style="{width: '100%'}"
          ></el-input>
        </el-form-item>
        <el-form-item label="法人姓名" prop="corporateName" label-width="180px">
          <el-input v-model="subForm.corporateName" placeholder="请输入法人姓名" show-word-limit :maxlength="10"
                    clearable v-no-whitespace
                    :style="{width: '100%'}"
          ></el-input>
        </el-form-item>
        <el-form-item label="法人联系方式" prop="corporatePhone" label-width="180px">
          <el-input v-model="subForm.corporatePhone" placeholder="请输入法人联系方式" show-word-limit :maxlength="11"
                    clearable v-no-whitespace
                    :style="{width: '100%'}"
          ></el-input>
        </el-form-item>
        <el-form-item label="社会统一征信代码" prop="socialUnifiedCreditCode" label-width="180px">
          <el-input v-model="subForm.socialUnifiedCreditCode" placeholder="请输入社会统一征信代码" show-word-limit
                    :maxlength="20" clearable @blur="checkIsExistSubName" v-no-whitespace
                    :style="{width: '100%'}"
          ></el-input>
        </el-form-item>
        <el-form-item label="分包商负责人" prop="subPrincipal" label-width="180px">
          <el-input v-model="subForm.subPrincipal" placeholder="请输入分包商负责人" show-word-limit
                    :maxlength="10" clearable v-no-whitespace
                    :style="{width: '100%'}"
          ></el-input>
        </el-form-item>
        <el-form-item label="分包商负责人联系方式" prop="subPrincipalPhone" label-width="180px">
          <el-input v-model="subForm.subPrincipalPhone" placeholder="请输入分包商负责人联系方式" show-word-limit
                    :maxlength="11" clearable v-no-whitespace
                    :style="{width: '100%'}"
          ></el-input>
        </el-form-item>
        <el-form-item label="分包商负责人身份证" prop="subIdCard" label-width="180px">
          <el-input v-model="subForm.subIdCard" 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">
        <el-button type="primary" @click="submitSubForm" v-preventReClick="5000">提 交</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { getSubList } from '@/api/pro/outsourcingPro'
import { checkIsExistSubName, addInfo ,sendSubNotice,delSub} from '@/api/pro/subManagement/subList'

import { dictTableOption } from '@/api/tool/select'
import numberUtils from '@/utils/validate'
import { hideSensitiveInfo } from '@/utils/bonus'
import { encryptCBC } from '@/utils/aescbc'

export default {
  name: 'Post',
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 工程表格数据
      subList: [],
      //工程类型下拉选
      statusDict: [
        {
          label: '已入场',
          value: 1
        },
        {
          label: '未入场',
          value: 0
        }
      ],
      // 是否显示弹出层
      subOpen: false,
      createTime: undefined,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        subName: undefined,
        status: undefined,
        startDate: undefined,
        endDate: undefined
      },
      // 表单参数
      subForm: {},
      // 表单校验
      subRules: {
        subName: [
          { required: true, message: '分包商单位名称不能为空', trigger: 'blur' }
        ],
        address: [
          { 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'
          }
        ],
        subPrincipal: [
          { required: true, message: '分包商负责人不能为空', trigger: 'blur' }
        ],
        subPrincipalPhone: [
          { required: true, validator:numberUtils.checkPhone, trigger: 'blur' },
        ],
        subIdCard: [
          { required: true, validator:numberUtils.checkIdCardNumber, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    hideSensitiveInfo,
    //判断是否选择工程创建时间
    judgeTime() {
      if (this.createTime !== undefined) {
        this.queryParams.startDate = this.createTime[0]
        this.queryParams.endDate = this.createTime[1]
      }
    },
    /** 查询工程列表 */
    getList() {
      this.loading = true
      this.judgeTime()
      this.queryParams.proId = this.$store.state.user.thisIds.proId
      this.queryParams.consId = this.$store.state.user.thisIds.consId
      this.queryParams.consUuid = this.$store.state.user.thisIds.consUuid
      this.queryParams.supUuid = this.$store.state.user.thisIds.supUuid

      getSubList(this.queryParams).then(response => {
        this.subList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    //获取工程类型下拉选
    getProType() {
      const params = {
        dictType: 'sys_pro_type',
        dictValue: ''
      }
      dictTableOption(params).then(response => {
        this.proTypeDict = response.data
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.subForm = {
        subName: undefined,
        address: undefined,
        corporateName: undefined,
        corporatePhone: undefined,
        socialUnifiedCreditCode: undefined,
        subPrincipal: undefined,
        subPrincipalPhone: undefined
      }
      this.resetForm('subForm')
      this.subOpen = false
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.judgeTime()
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.queryParams.startDate = undefined
      this.queryParams.endDate = undefined
      this.createTime = undefined
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.proId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.subOpen = true
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.$router.push('/system/outsourcing-subDetailsInfo-auth/subDetailsInfo/' + encryptCBC(JSON.stringify({
        proId: row.proId,
        consUuid: row.consUuid,
        supUuid: row.supUuid ? row.supUuid : "",
        subId: row.id,
        subUuid: row.subUuid,
        uuid: row.uuid
      })))
    },
    /** 入场通知按钮操作 */
    handleNotice(row) {
      const subName = row.subName
      let text = '确认将<span style="color: red">'+subName+'</span>（分包商）进行入场通知么？'
      this.$modal.confirm(text).then(async () => {
        try {
          await sendSubNotice({
            phone: row.subPrincipalPhone,
            proName: this.$store.state.user.thisIds.proName,
          });
          this.getList();
          this.$modal.msgSuccess('通知成功');
        } catch (error) {
          this.$modal.msgError('通知失败');
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const subId = row.id
      const subName = row.subName
      this.$modal.confirm('是否确认删除分包商名称为<span style="color: red">'+subName+'</span>的数据项？').then(function() {
        return delSub(subId)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.derive('project/outsourcingPro/exportSub', {
        ...this.queryParams
      }, `分包商列表.xlsx`)
    },
    /** 校验分包商单位名称是否存在 */
    //检查工程名称是否存在
    async checkIsExistSubName() {
      const params = {
        subName: this.subForm.subName,
        proId: this.$store.state.user.thisIds.proId,
        consUuid: this.$store.state.user.thisIds.consUuid,
        socialUnifiedCreditCode: this.subForm.socialUnifiedCreditCode
      }
      try {
        const response = await checkIsExistSubName(params)
        if (response.code === 500) {
          this.$message({
            message: response.msg,
            type: 'error'
          })
          // 返回 false 或者其他值，表示单位名称已存在
          return false
        } else {
          // 返回 true 或者其他值，表示单位名称不存在重复
          return true
        }
      } catch (error) {
        return false
      }
    },
    async submitSubForm() {
      this.$refs.subForm.validate(async(valid) => {
        if (!valid) {
          return false
        } else {
          // 前端验证通过，再进行唯一性检查
          const isExist = await this.checkIsExistSubName()
          if (isExist === false) {
            // 如果工程名称已存在，可以做出相应的提示或处理
            return
          }
          this.loading = true
          // TODO 提交表单
          this.subForm.proId = this.$store.state.user.thisIds.proId
          this.subForm.consUuid = this.$store.state.user.thisIds.consUuid
          this.subForm.supUuid = this.$store.state.user.thisIds.supUuid
          console.log(this.subForm)
          addInfo(this.subForm).then(response => {
            if (response.code === 200) {
              this.loading = false
              this.$message({
                message: '新建成功',
                type: 'success'
              })
              this.getList()
              //关闭tab页
              this.subOpen = false
            } else {
              this.loading = false
              this.$message({
                message: response.msg,
                type: 'error'
              })
            }
          })
        }
      })

    },
    subCancel() {

    }
  }
}
</script>
