<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" v-if="!notHasPermission">
          <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 import" @click.stop="batchImport">
            <img src="@/assets/images/project/project-bid-opening-record-import.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>
      </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"
          @handle-current-change="pageCurrentChange" ref="tableListComParent">
          <template slot="tenderAmountHeader">
            <div class="tender-amount-header">
              <span>投标金额（万元）</span>
              <div class="tender-amount-sort">
                <svg-icon icon-class="asc" :class="{'sort-active' : queryParams.isAsc == 'asc'}"
                  @click.stop="sortChange('tenderAmount','asc')"></svg-icon>
                <svg-icon icon-class="desc" :class="{'sort-active' : queryParams.isAsc == 'desc'}"
                  @click.stop="sortChange('tenderAmount','desc')"></svg-icon>
              </div>
            </div>
          </template>
          <template slot="tenderAmount" slot-scope="scope">
            <span>{{parseFloat(scope.row.tenderAmount) ? scope.row.tenderAmount : "--"}}</span>
          </template>
          <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-com :uploadOptions="uploadOptions" @success-upload="successUpload" @cancel-import="cancelimport"></batch-import-com>
  </div>
</template>
<script>
import skeleton from './skeleton';
import TableListCom from "@/components/TableListCom";
import BatchImportCom from "./BatchImportCom";
import { getBidOpeningRecordListApi, addBidOpeningRecordApi, modifyBidOpeningRecordApi, removeBidOpeningRecordApi } from "@/api/project/project";
import AddBidOpeningRecord from "./AddBidOpeningRecord.vue";
import { getToken } from "@/utils/auth";
export default {
  components: { skeleton, TableListCom, AddBidOpeningRecord, BatchImportCom },
  name: "bidOpeningRecord",
  props: {
    detailId: {
      type: Number,
      default: 0
    },
    projectData: {
      type: Object,
      default: () => ({})
    },
    isDisabled: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    projectData: {
      handler(newValue, oldValue) {
        this.projectDetail = newValue;
      }
    },
    isDisabled: {
      handler(newValue, oldValue) {
        this.notHasPermission = newValue;
      }
    }
  },
  data() {
    // 必填字符串长度验证
    function tendererStrLengthValidator(target) {
      return function (rule, value, callback) {
        if (!value && !value?.toString()?.trim()) {
          return callback(new Error(`请输入${target}`));
        }
        return callback();
      };
    };
    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 {
      // 项目详情
      projectDetail: this.projectData,
      // 是否拥有权限
      notHasPermission: this.isDisabled,
      title: "新增开标记录",
      // 加载状态
      isLoadingData: false,
      // 列表列数据
      formColum: [
        { label: '投标人', prop: 'tenderer', minWidth: "468px" },
        { label: '企业性质', prop: 'tendererNature', minWidth: "96px" },
        { label: '项目经理', prop: 'businessManager', minWidth: "115px" },
        { label: '联系方式', prop: 'contact', width: "133px", },
        { label: '投标金额（万元）', prop: 'tenderAmount', width: "168px", slot: true, slotHeader: true, slotName: "tenderAmountHeader" },
      ],
      needSelection: {
        flag: true,
        width: "39px",
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        orderByColumn: "tenderAmount",
        isAsc: "asc",
        businessId: this.detailId ? this.detailId : parseInt(this.$route.query.id),
      },
      tableDataTotal: 0,
      tableDataList: [],
      // 表单验证规则
      // 表单数据
      formData: {
        businessId: this.detailId ? this.detailId : parseInt(this.$route.query.id),
        tenderer: "",
        tendererNature: "",
        businessManager: "",
        contact: "",
        tenderAmount: ""
      },
      formRules: {
        tenderer: [{ required: true, trigger: "blur", validator: tendererStrLengthValidator("投标人") }],
        tendererNature: [{ trigger: "blur", validator: requiredStrLengthValidator("企业性质") }],
        businessManager: [{ trigger: ["change", "blur"], validator: strLengthValidator("项目经理") }],
        contact: [{ trigger: ["blur"], validator: phoneNumberValidator }],
        tenderAmount: [{ trigger: ["blur"], validator: amountValidator }],
      },
      selectionArray: [],
      // 展示新增弹窗
      showAddDialog: false,
      // 导入开标记录配置
      uploadOptions: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "导入开标记录",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + `${process.env.ENV == "production" ? "business/open/tender/importData/" : "/business/open/tender/importData/"}${this.detailId ? this.detailId : parseInt(this.$route.query.id)}`,
        // 展示上传结果
        showResult: false,
        // 模板下载地址
        fileTemplateUrl: "/file/bidOpeningRecordTemplate.xlsx",
        // 模板名称
        fileName: "bidOpeningRecordTemplate"
      },
    };
  },
  //可访问data属性
  created() {
    this.dataInit();
  },
  //计算集
  computed: {

  },
  //方法集
  methods: {
    async dataInit() {
      try {
        if (!this.notHasPermission) {
          this.formColum.push({ label: '操作', prop: 'action-field-bar', width: "151px", fixed: "right" });
        } else {
          this.needSelection = {
            flag: false,
            width: "39px",
          };
        }
        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 temp = JSON.parse(JSON.stringify(this.formData));
        const keys = Object.keys(temp);
        const flag = keys.every(key => ((key == "id" || key == "businessId") ? true : (!temp[key] && temp[key] != "0") ? true : false));
        if (flag) {
          return this.dialogClose();
        }
        const result = this.formData.id ? await modifyBidOpeningRecordApi(this.formData) : await addBidOpeningRecordApi(this.formData);
        if (result.code == 200) {
          this.$message.success(`${this.formData.id ? "修改成功!" : "新增成功!"}`);
          this.dialogClose();
          await this.getTableList();
        } else {
          this.$message.error(`${result.msg}`);
        }
      } catch (error) {
        console.log(error);
      }
    },
    // 重置复选框
    async resetSelection() {
      try {
        await this.$nextTick();
        // 清空复选框选项
        this.$refs["tableListComParent"]?.$refs["tableRef"] ? this.$refs["tableListComParent"].$refs["tableRef"].clearSelection() : null;
        this.selectionArray = [];
      } catch (error) {
        console.log(error);
      }
    },
    // 批量删除
    async batchDeletion(id) {
      if (!this.selectionArray?.length && !id) return;
      this.$confirm('此操作将会删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const array = id ? [{ id }] : this.selectionArray;
          const result = await removeBidOpeningRecordApi((array.map(item => item.id)).join(","));
          if (result.code == 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getTableList();
          }
        } catch (error) {
          console.log(error);
        }
      }).catch(() => { });
    },
    // 复选框选中
    selectionChange(array) {
      this.selectionArray = array;
    },
    hasConditions() {
      const { pageNum, pageSize, orderByColumn, isAsc } = this.queryParams;
      this.getTableList(pageNum, pageSize, orderByColumn, isAsc);
    },
    // 列排序
    sortChange(prop, order) {
      this.queryParams.orderByColumn = prop;
      if (order == "asc") {
        this.queryParams.isAsc = "asc";
      } else if (order == "desc") {
        this.queryParams.isAsc = "desc";
      }
      this.hasConditions();
    },
    // 翻页
    pageCurrentChange(page) {
      this.queryParams.pageNum = page;
      this.hasConditions();
    },
    // 批量导入
    batchImport() {
      this.uploadOptions.open = true;
    },
    cancelimport() {
      this.uploadOptions.open = false;
    },
    // 导入成功
    successUpload() {
      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: 4px;
          }

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

    .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;
          }
        }
      }

      .tender-amount-header {
        display: flex;
        align-items: center;

        .tender-amount-sort {
          margin-left: 5px;
          display: flex;
          flex-direction: column;

          .svg-icon {
            width: 10px;
            height: 10px;
            fill: #8bd1ff;
            cursor: pointer;
            &:hover {
              fill: #0081ff;
            }
            &.sort-active {
              fill: #0081ff;
            }
          }
        }
      }
    }
  }
}
</style>
