<template>
  <div class="bid-opening-record">
    <div class="bid-opening-record-inner">
      <!-- 查询功能 -->
      <div class="search-form-container">
        <div class="left-form-title">基本信息</div>
        <div class="right-form-btn-box">
          <div class="search-btn add" @click.stop="addBidOpeningRecord">
            <img src="@/assets/images/project/project-bid-opening-record-add.svg" alt="">
            <span>新增</span>
          </div>
          <div class="search-btn remove" @click.stop="batchDeletion()">
            <img src="@/assets/images/project/project-bid-opening-record-remove.svg" alt="">
            <span>批量删除</span>
          </div>
          <div class="search-btn import" @click.stop="batchImport">
            <img src="@/assets/images/project/project-bid-opening-record-import.svg" alt="">
            <span>批量导入</span>
          </div>
        </div>
      </div>
      <!-- 骨架屏 -->
      <skeleton v-if="isLoadingData"></skeleton>
      <!-- 列表 -->
      <div class="table-data-list-container" v-else-if="!isLoadingData || !tableDataList.length">
        <table-list-com :formColum="formColum" :queryParams="queryParams" :tableData="tableDataList" :tableDataTotal="tableDataTotal"
          :needSelection="needSelection" :stickyHeader="{offsetTop:'48px',offsetBottom : '10px'}" @selectionChange="selectionChange"
          @sort-change="sortChange" @handle-current-change="pageCurrentChange" ref="tableListComParent">
          <template slot="action-field-bar" slot-scope="scope">
            <div class="action-field-bar-container">
              <span class="action-field-bar-btn modify" @click.stop="modifyBidOpeningRecord(scope.row)">编辑</span>
              <span class="action-field-bar-btn remove" @click.stop="batchDeletion(scope.row.id)">删除</span>
            </div>
          </template>
        </table-list-com>
      </div>
    </div>

    <!-- 新增开标记录弹窗 -->
    <add-bid-opening-record :show="showAddDialog" :title="title" @dialogClose="dialogClose" @validatorSuccess="validatorSuccess"
      :formRules="formRules" :formData="formData"></add-bid-opening-record>

    <!-- 导入弹窗 -->
    <batch-import-reset v-if="showImport" :importtype="types" @cancels="cancelimport" @getdatas="getdatas"></batch-import-reset>
  </div>
</template>
<script>
import skeleton from './skeleton';
import TableListCom from "@/components/TableListCom";
import BatchImportReset from "./batchImportReset";
import { getBidOpeningRecordListApi, addBidOpeningRecordApi, modifyBidOpeningRecordApi, removeBidOpeningRecordApi } from "@/api/project/project";
import AddBidOpeningRecord from "./AddBidOpeningRecord.vue";
export default {
  components: { skeleton, TableListCom, AddBidOpeningRecord, BatchImportReset },
  name: "bidOpeningRecord",
  data() {
    // 必填字符串长度验证
    function requiredStrLengthValidator(target) {
      return function (rule, value, callback) {
        if (!value || !value?.toString()?.trim()) {
          return callback(new Error(`请输入${target}`));
        }
        return callback();
      };
    };
    // 字符串长度验证
    function strLengthValidator(target) {
      return function (rule, value, callback) {
        if (value && !value?.toString()?.trim()) {
          return callback(new Error(`请输入${target}`));
        }
        return callback();
      };
    };
    // 电话验证
    const phoneReg = /^1[3-9]\d{9}$/;
    function phoneNumberValidator(rule, value, callback) {
      if (value && !value?.toString()?.trim()) {
        return callback(new Error(`请输入联系方式`));
      }
      if (value && !phoneReg.test(value)) {
        return callback(new Error(`请输入正确的手机号码`));
      }
      return callback();
    };
    // 金额验证
    const amountReg = /^(?!0\d)\d+(\.\d+)?$/;
    function amountValidator(rule, value, callback) {
      if ((!value && value != "0") || !value?.toString()?.trim()) {
        return callback(new Error(`请输入投标金额`));
      }
      if (value && !amountReg.test(value)) {
        return callback(new Error("请输入正确的投标金额"));
      }
      return callback();
    }
    return {
      title: "新增开标记录",
      // 加载状态
      isLoadingData: false,
      // 列表列数据
      formColum: [
        { label: '投标人', prop: 'tenderer', width: "468px" },
        { label: '企业性质', prop: 'tendererNature', width: "96px" },
        { label: '项目经理', prop: 'businessManager', width: "115px" },
        { label: '联系方式', prop: 'contact', width: "133px" },
        { label: '投标金额（万元）', prop: 'tenderAmount', width: "168px", sortable: "custom" },
        { label: '操作', prop: 'action-field-bar', minWidth: "151px", fixed: "right" },
      ],
      needSelection: {
        flag: true,
        width: "39px",
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        orderByColumn: "tenderAmount",
        isAsc: "asc",
        businessId: this.$route.query.id,
      },
      tableDataTotal: 0,
      tableDataList: [],
      // 表单验证规则
      // 表单数据
      formData: {
        businessId: this.$route.query.id,
        tenderer: "",
        tendererNature: "",
        businessManager: "",
        contact: "",
        tenderAmount: ""
      },
      formRules: {
        tenderer: [{ required: true, trigger: "blur", validator: requiredStrLengthValidator("投标人") }],
        tendererNature: [{ required: true, trigger: "blur", validator: requiredStrLengthValidator("企业性质") }],
        businessManager: [{ trigger: ["change", "blur"], validator: strLengthValidator("项目经理") }],
        contact: [{ trigger: ["blur"], validator: phoneNumberValidator }],
        tenderAmount: [{ required: true, trigger: ["blur"], validator: amountValidator }],
      },
      selectionArray: [],
      // 展示新增弹窗
      showAddDialog: false,
      // 导入弹窗
      showImport: false
    };
  },
  //可访问data属性
  created() {
    this.dataInit();
  },
  //计算集
  computed: {

  },
  //方法集
  methods: {
    async dataInit() {
      try {
        await this.getTableList();
      } catch (error) {
        console.log(error);
      }
    },
    async getTableList(pageNum, pageSize, orderByColumn, isAsc) {
      try {
        this.searchCheck(pageNum, pageSize, orderByColumn, isAsc);
        this.isLoadingData = true;
        const result = await getBidOpeningRecordListApi(this.queryParams);
        if (result.code == 200) {
          this.tableDataList = result.rows;
          this.tableDataTotal = result.total;
        }
      } catch (error) {
        console.log(error);
      } finally {
        this.isLoadingData = false;
        await this.resetSelection();
      }
    },
    searchCheck(pageNum, pageSize, orderByColumn, isAsc) {
      if (!pageNum) {
        this.queryParams.pageNum = 1;
      }
      if (!pageSize) {
        this.queryParams.pageSize = 20;
      }
      if (!orderByColumn) {
        this.queryParams.orderByColumn = "tenderAmount";
      }
      if (!isAsc) {
        this.queryParams.isAsc = "asc";
      }
    },
    addBidOpeningRecord() {
      this.title = "新增开标记录";
      this.showAddDialog = true;
    },
    // 修改开标记录
    modifyBidOpeningRecord({ businessId, businessManager, contact, id, tenderAmount, tenderer, tendererNature }) {
      const params = {
        businessId,
        businessManager,
        contact,
        id,
        tenderAmount,
        tenderer,
        tendererNature
      };
      this.formData = { ...this.formData, ...params };
      this.title = "修改开标记录";
      this.showAddDialog = true;
    },
    dialogClose() {
      this.showAddDialog = false;
      this.formData = this.$options.data.call(this).formData;
    },
    // 验证通过提交数据
    async validatorSuccess() {
      try {
        const result = this.formData.id ? await modifyBidOpeningRecordApi(this.formData) : await addBidOpeningRecordApi(this.formData);
        if (result.code == 200) {
          console.log(result);
          this.dialogClose();
          await this.getTableList();
        }
      } catch (error) {
        console.log(error);
      }
    },
    // 重置复选框
    async resetSelection() {
      try {
        await this.$nextTick();
        // 清空复选框选项
        this.$refs["tableListComParent"].$refs["tableRef"].clearSelection();
        this.selectionArray = [];
      } catch (error) {
        console.log(error);
      }
    },
    // 批量删除
    async batchDeletion(id) {
      try {
        if (!this.selectionArray?.length && !id) return;
        const array = id ? [{ id }] : this.selectionArray;
        const result = await removeBidOpeningRecordApi({
          ids: (array.map(item => item.id))
        });
        if (result.code == 200) {
          this.getTableList();
        }
      } catch (error) {
        console.log(error);
      }
    },
    // 复选框选中
    selectionChange(array) {
      this.selectionArray = array;
    },
    hasConditions() {
      const { pageNum, pageSize, orderByColumn, isAsc } = this.queryParams;
      this.getTableList(pageNum, pageSize, orderByColumn, isAsc);
    },
    // 列排序
    sortChange({ column, order, prop }) {
      this.queryParams.orderByColumn = prop;
      if (order == "ascending") {
        this.queryParams.isAsc = "asc";
      } else if (order == "descending") {
        this.queryParams.isAsc = "desc";
      }
      this.hasConditions();
    },
    // 翻页
    pageCurrentChange(page) {
      this.queryParams.pageNum = page;
      this.hasConditions();
    },
    // 批量导入
    batchImport() {
      this.showImport = true;
    },
    cancelimport() {
      this.showImport = false;
    },
    getdatas() {
      this.getTableList();
    }
  },
}
</script>
<style lang="scss" scoped>
.bid-opening-record {
  width: 100%;
  background: #fff;
  padding: 16px;
  box-sizing: border-box;

  .bid-opening-record-inner {
    width: 100%;
    height: 100%;

    .search-form-container {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .left-form-title {
        font-size: 16px;
        line-height: 16px;
        font-weight: bold;
        color: #232323;
        position: relative;
        padding-left: 8px;
        box-sizing: border-box;

        &::before {
          content: "";
          position: absolute;
          left: 0px;
          width: 2px;
          height: 14px;
          background: #445781;
        }
      }

      .right-form-btn-box {
        display: flex;
        align-items: center;

        & > .search-btn:first-of-type {
          margin-left: 0px;
        }

        .search-btn {
          height: 32px;
          display: flex;
          align-items: center;
          justify-content: center;
          padding: 0px 16px;
          box-sizing: border-box;
          font-size: 14px;
          margin-left: 12px;
          cursor: pointer;

          & > span {
            margin-left: 8px;
          }

          & > img {
            width: 14px;
            height: 14px;
          }

          &.add {
            background: #0081ff;
            border-radius: 4px;
            color: #fff;
          }

          &.remove {
            background: #fff;
            border: 1px solid #ff3c3c;
            color: #ff3c3c;
            border-radius: 2px;
          }

          &.import {
            background: #fff;
            border: 1px solid #d9d9d9;
            color: #232323;
            border-radius: 2px;
          }
        }
      }
    }

    .table-data-list-container {
      width: 100%;
      margin-top: 16px;

      .action-field-bar-container {
        display: flex;

        .action-field-bar-btn {
          font-size: 12px;
          font-weight: 400;
          line-height: 20px;
          padding: 0px 12px;
          box-sizing: border-box;
          cursor: pointer;

          &.modify {
            color: #0081ff;
          }
          &.remove {
            color: #ff3c3c;
          }
        }
      }
    }
  }
}
</style>
