<template>
  <div class="app-container">
    <card-table :loading="loading" :modalData="quotationList" :searchParams="queryParams" :tableSearch="true" labelWidth="120px" @columnSearch="handleQuery" @pagination="getList" :row-key="rowKey" :children="children" @resetList="resetQuery"
                @selection-change="handleSelectionChange">
      <template #operations="{ selections }">
        <el-button icon="el-icon-plus" plain size="mini" type="primary" @click="handleAdd">{{ $t('quotation.addQuotation') }}
        </el-button>
        <el-button icon="el-icon-download" plain size="mini" type="warning" @click="handleExport">{{ $t('common.export') }}
        </el-button>
        <el-button icon="el-icon-plus" plain size="mini" type="primary" v-loading="copyVersionLoading" @click="copyVersion">{{ $t('quotation.copyVersion') }}
        </el-button>
      </template>
      <template #default="{ list }">
        <el-table-column align="center" type="selection" width="55"/>
        <!--报价编号-->
        <Column :label="$t('quotation.quotationNo')" :showSearch="true" prop="quotationNo" :min-width="200"/>
        <!--版本号-->
        <Column :label="$t('common.version')" prop="version"/>
        <!--项目名称-->
        <Column :label="$t('project.projectName')" :showSearch="true" prop="projectName"/>
        <!--项目类型-->
        <Column :label="$t('project.type')" prop="type" :showSearch="true" searchType="select" :searchDict="dict.type.project_type" width="200px" :selectMore="true"/>
        <!--项目细分市场-->
        <Column :label="$t('project.projectSegments')" prop="segmentedMarket" :showSearch="true" searchType="select" :searchDict="dict.type.project_market" width="200px" :selectMore="true"/>
        <!--国家-->
        <Column :label="$t('project.countryId')" prop="countryId" :showSearch="true" searchType="select" :searchDict="countryList" width="200px" :selectMore="true"/>
        <!--城市-->
        <Column :label="$t('project.city')" prop="city" :showSearch="true" width="200px" :selectMore="true"/>
        <!--币种-->
        <Column :label="$t('project.currency')" prop="currencyId" :showSearch="true" searchType="select" :searchDict="dict.type.currency_type" width="200px" :selectMore="true"/>
        <!--梯形-->
        <Column :label="$t('quotation.suitModel')" prop="elevatorModel" :showSearch="true"/>
        <!--报价者-->
        <Column :label="$t('quotation.quoter')" prop="nickName" :showSearch="true"/>
        <!--最终价格-->
        <Column :label="$t('quotation.finalPrice')" prop="finalPrice"/>
        <!--附加费用-->
        <Column :label="$t('quotation.additionalCost')" prop="additionalFees"/>
        <!--提交时间-->
        <Column :label="$t('quotation.submitTime')" prop="submitTime" align="center" :min-width="300" :searchParams="queryParams" :showSearch="true" searchType="dateRange"/>
        <!--报价状态-->
        <Column :label="$t('quotation.quotationStatus')" prop="quotationStatus" :min-width="250" :searchDict="dict.type.quotation_status" :showSearch="true" :selectMore="true" searchType="select">
          <template #default="{ row }">
            <ColorDictTag :bgc="statusColorMap[row.quotationStatus].bgc" :label="convertStatus(row.quotationStatus)" :label-color="statusColorMap[row.quotationStatus].color"
                          @click.native="main.showAuditHistory(row.id, [AUDIT_FLOW.QUOTATION, AUDIT_FLOW.BARGAIN].join(','))"/>
          </template>
        </Column>
        <!--操作-->
        <Column :label="$t('common.operate')" :min-width="300" :showSearch="true" fixed="right" searchType="operate">
          <template #default="{ row }">
            <!--            查看详情-->
            <!--            <el-button v-hasPermi="['business:quotation:detail']" icon="el-icon-view" size="mini" type="text" v-if="quotationIn(row,['8'])"-->
            <!--                       @click="handleDetail(row)">{{ $t('common.view') }}详情-->
            <!--            </el-button>-->
            <!--            查看-->
            <el-button v-hasPermi="['business:quotation:detail']" icon="el-icon-view" size="mini" type="text"
                       @click="handleView(row,0)">{{ $t('common.view') }}
            </el-button>
            <!--            编辑-->
            <el-button v-hasPermi="['bt:business:quotation:detail']" icon="el-icon-edit" size="mini" type="text" v-if="quotationIn(row,['0'])"
                       @click="handleUpdate(row)">{{ $t('common.edit') }}
            </el-button>
            <!--            技术评审-->
            <el-button v-hasPermi="['business:quotation:detail']" size="mini" v-if="quotationIn(row,['1']) && isAuditor(row.flow)"
                       type="text" @click="handleView(row,1)">{{ $t('quotation.techReview') }}
            </el-button>
            <!--            采购询价-->
            <el-button v-hasPermi="['bt:business:quotation:detail']" size="mini" v-if="quotationIn(row,['3']) && isAuditor(row.flow)"
                       type="text" @click="handleView(row,2)">{{ $t('quotation.buyerInquiry') }}
            </el-button>
            <!--            财务询价-->
            <el-button v-hasPermi="['business:quotation:detail']" size="mini" v-if="quotationIn(row,['4']) && isAuditor(row.flow)"
                       type="text" @click="handleView(row,3)">{{ $t('quotation.treasureInquiry') }}
            </el-button>
            <!--            销售确认-->
            <el-button v-hasPermi="['bt:business:quotation:view']" size="mini" v-if="quotationIn(row,['5']) && isAuditor(row.flow)"
                       type="text" @click="handleView(row,4)">{{ $t('quotation.salesConfirm') }}
            </el-button>
            <!--            议价-->
            <el-button v-hasPermi="['business:quotation:detail']" size="mini" type="text" v-if="quotationIn(row, ['6','10'])"
                       @click="handleBargain(row,0)">{{ $t('quotation.negotiatedPrice') }}
            </el-button>
            <!--            议价审批-->
            <el-button v-hasPermi="['business:quotation:negotiatedPrice']" size="mini" type="text" v-if="quotationIn(row,['7'])"
                       @click="handleBargain(row,1)">{{ $t('quotation.bargainApproval') }}
            </el-button>
            <!--            议价确认-->
            <el-button v-hasPermi="['business:quotation:negotiatedPrice']" size="mini" type="text" v-if="quotationIn(row,['8'])"
                       @click="handleBargain(row,2)">{{ $t('quotation.bargainConfirm') }}
            </el-button>
            <!--            附加费用-->
            <el-button v-hasPermi="['business:quotation:additionalCost']" size="mini" type="text" v-if="quotationIn(row,['11'])"
                       @click="showAdditionalCost(row)">{{ $t('quotation.additionalCost') }}
            </el-button>
          </template>
        </Column>
      </template>
    </card-table>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="$t('quotation.additionalCost')" :visible.sync="open" :close-on-click-modal="false" width="60%">
      <!--      <div class="card-title mb16">{{ $t('lead.baseInfo') }}</div>-->
      <!--      <div>-->
      <el-form :model="form" label-width="100px">
        <el-row>
          <el-col :span="12">
            <!--项目编号 -->
            <el-form-item :label="$t('project.projectNo')" prop="projectNo">
              <el-input :disabled="true" v-model="form.projectNo" maxlength="100" :placeholder="$t('common.pleaseInput') + $t('project.projectNo')"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!--项目名称 -->
            <el-form-item :label="$t('project.name')" prop="name">
              <el-input :disabled="true" v-model="form.projectName" maxlength="100" :placeholder="$t('common.pleaseInput') + $t('project.projectNo')"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <!--币种 -->
            <el-form-item :label="$t('project.currency')" prop="currency">
              <el-select :disabled="true" v-model="form.currencyId" class="w-100" :placeholder="$t('common.pleaseSelect') + $t('project.currency')">
                <el-option v-for="dict in dict.type.currency_type" :key="Number(dict.value)" :label="dict.label" :value="Number(dict.value)"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!--报价编号 -->
            <el-form-item :label="$t('quotation.quotationNo')" prop="quotationNo">
              <el-input :disabled="true" v-model="form.quotationNo" maxlength="100" :placeholder="$t('common.pleaseInput') + $t('quotation.quotationNo')"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <!--版本 -->
            <el-form-item :label="$t('common.version')" prop="accountName">
              <el-input :disabled="true" v-model="form.version" maxlength="100" :placeholder="$t('common.pleaseInput') + $t('common.version')"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
          </el-col>
        </el-row>
      </el-form>
      <!--      </div>-->
      <!--      <div class="card-title mb16">{{ $t('quotation.additionalCost') }}</div>-->
      <div class="ml20">
        <div v-if="!additionalCostDisabledFlag">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="addLine">
            {{ $t('quotation.addAdditionalCost') }}
          </el-button>
          <el-button size="mini" plain type="warning" icon="el-icon-delete" @click="deleteLine" :disabled="deleteDisabled">
            {{ $t('quotation.delAdditionalCost') }}
          </el-button>
        </div>
        <el-table :data="additionalCostList" @selection-change="additionalCostSelection" max-height="280px" v-loading="tableLoading">
          <el-table-column type="selection" width="55" v-if="!additionalCostDisabledFlag"></el-table-column>
          <el-table-column prop="feeName" :label="$t('quotation.feeName')" min-width="140px">
            <template slot-scope="scope">
              <el-select v-model="scope.row.feesType" :placeholder="$t('common.pleaseSelect') + $t('quotation.feeName')" :disabled="additionalCostDisabledFlag">
                <el-option v-for="dict in dict.type.fees_type" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="additionalFees" :label="$t('quotation.amountRmb')" min-width="190px">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.additionalFees" :disabled="additionalCostDisabledFlag" :precision="4" :min="0" :placeholder="$t('common.pleaseInput') + $t('quotation.amountRmb')" @change="amountChange(scope.row)"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column prop="convertedAmount" :label="$t('quotation.convertedAmount')" min-width="190px">
          </el-table-column>
          <el-table-column prop="remark" :label="$t('common.remark')" min-width="200px">
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark" :disabled="additionalCostDisabledFlag" :placeholder="$t('common.pleaseInput') + $t('common.remark')"></el-input>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" icon="el-icon-circle-check" v-if="!additionalCostDisabledFlag">{{ $t('common.confirm') }}</el-button>
        <el-button @click="cancel" icon="el-icon-remove-outline">{{ $t('common.cancel') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Column from "@/components/element/table/Column.vue";
import ColorDictTag from "@/views/crmManagement/lead/ColorDictTag/index.vue";
import {getAllNationList} from "@/api/user/country";
import {listQuotation, copyVersion} from "@/api/business/quotation/quotation";
import {listByQuotationId, batchAdd} from "@/api/business/quotation/fees";
import {parseTime} from "@/utils/ruoyi";
import {mapGetters} from "vuex";
import {getUsableCurrencyRate} from "@/api/user/currency";

const labelSuffix = {
  chinese: "",
  english: "US",
  russia: "RU",
  spanish: "ES",
};

const statusColorMap = {
  0: {
    color: "#24CA5D",
    bgc: "rgba(24,199,84,0.12)",
  },
  1: {
    color: "#8B71FD",
    bgc: "rgba(139,113,253,0.12)",
  },
  2: {
    color: "#0DCCD7",
    bgc: "rgba(13,204,215,0.12)",
  },
  3: {
    color: "#218AFC",
    bgc: "#E5F1FF",
  },
  4: {
    color: "#FC5821",
    bgc: "rgba(252,88,33,0.12)",
  },
  5: {
    color: "#AD2BBF",
    bgc: "rgba(163,32,181,0.12)",
  },
  6: {
    color: "#0B8B21",
    bgc: "rgba(11,139,33,0.12)",
  },
  7: {
    color: '#D71943',
    bgc: '#FAEDED'
  },
  8: {
    color: '#D71943',
    bgc: '#FAEDED'
  },
  9: {
    color: '#D71943',
    bgc: '#FAEDED'
  },
  10: {
    color: '#D71943',
    bgc: '#FAEDED'
  },
  11: {
    color: '#D71943',
    bgc: '#FAEDED'
  },
  12: {
    color: '#D71943',
    bgc: '#FAEDED'
  },
  undefined: {
    color: "#D71943",
    bgc: "#FAEDED",
  },
  null: {
    color: "#D71943",
    bgc: "#FAEDED",
  },
};

export default {
  name: "Quotation",
  inject: ["main"],
  components: {Column, ColorDictTag},
  dicts: [
    "quotation_status",
    "project_type",
    "project_market",
    "currency_type",
    "fees_type",
  ],
  data() {
    return {
      additionalCostDisabledFlag: false,
      rowKey: "id",
      children: "children",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      quotationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      countryList: [],
      form: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
        quotationNo: null,
        projectName: null,
        type: [],
        segmentedMarket: [],
        countryId: [],
        city: null,
        currencyId: [],
        elevatorMode: null,
        nickName: null,
        createTime: [],
        quotationStatus: [],
      },
      statusColorMap: statusColorMap,
      additionalCostList: [],
      deleteDisabled: true,
      multipleSelection: [],
      language: null,
      copyVersionLoading: false,
      // 汇率
      exchangeRate: 0,
      tableLoading: false,
    };
  },
  async created() {
    this.language = this.$i18n.locale;
    this.getNationList();
    const {businessNo} = this.$route.query;
    if (businessNo) {
      this.queryParams.quotationNo = businessNo
    }
    this.getList();
  },
  computed: {
    ...mapGetters(["userId"]),
    localLabelSuffix() {
      return labelSuffix[this.$i18n.locale] || "";
    },
  },
  activated() {
    const {businessNo} = this.$route.query;
    if (businessNo) {
      this.queryParams.quotationNo = businessNo
    }
    this.getList();
  },
  methods: {
    amountChange(row) {
      console.log("行金额变更", row);
      if (row.additionalFees != null) {
        row.convertedAmount = this.exchangeRate * row.additionalFees;
      } else {
        row.convertedAmount = "-";
      }
    },
    additionalCostSelection(selection) {
      this.multipleSelection = selection;
      this.deleteDisabled = this.multipleSelection.length === 0;
    },
    addLine() {
      this.additionalCostList.push({feesType: '0', exchange_rate: 9.00})
      for (let i = 0; i < this.additionalCostList.length; i++) {
        this.additionalCostList[i].index = i;
      }
    },
    deleteLine() {
      this.multipleSelection.forEach((account) => {
        this.additionalCostList = this.additionalCostList.filter((item) => {
          return item.index !== account.index;
        });
      });
      for (let i = 0; i < this.additionalCostList.length; i++) {
        this.additionalCostList[i].index = i;
      }
    },
    async showAdditionalCost(row) {
      // 查询汇率
      let res = await getUsableCurrencyRate(row.currencyId)
      this.exchangeRate = res.data.exchangeRate
      this.additionalCostList = [];
      this.open = true;
      this.form = {
        quotationId: row.id,
        projectNo: row.projectNo,
        projectName: row.projectName,
        currencyId: row.currencyId,
        quotationNo: row.quotationNo,
        version: row.version,
      };
      this.tableLoading = true;

      console.log("报价id", this.form);
      listByQuotationId(this.form.quotationId)
        .then((response) => {
          this.additionalCostList = response.rows;
          this.additionalCostList.forEach((item) => {
            item.convertedAmount = item.exchangeRate * item.additionalFees;
          });
        }).finally(() => {
        this.tableLoading = false;
      });
    },
    cancel() {
      this.open = false;
    },
    // 附加费用提交
    submitForm() {
      let additionalFeesList = [];
      if (this.additionalCostList.length > 0) {
        this.additionalCostList.forEach((item) => {
          additionalFeesList.push({
            quotationId: this.form.quotationId,
            feesType: item.feesType,
            currencyId: this.form.currencyId,
            exchangeRate: this.exchangeRate,
            additionalFees: item.additionalFees,
            remark: item.remark,
          });
        });
      }

      let param = {
        quotationId: this.form.quotationId,
        additionalFeesList: additionalFeesList,
      };
      console.log("提交参数", param);
      batchAdd(param).then((response) => {
        this.$modal.msgSuccess(this.$t("common.operateSuccess"));
        this.open = false;
      });
    },
    copyVersion() {
      console.log("选中行", this.ids);
      this.copyVersionLoading = true;
      copyVersion({ids: this.ids})
        .then((response) => {
        })
        .finally(() => {
          this.copyVersionLoading = false;
        });
    },
    // value 转 label
    convertStatus(status) {
      if (!status) return "-";
      const check = this.dict.type.quotation_status.filter(
        (item) => item.value == status
      );
      if (check && check.length > 0) {
        return check[0].label;
      } else {
        return "-";
      }
    },
    /** 获取所有国家列表 */
    getNationList() {
      getAllNationList().then((response) => {
        this.countryList = response.data.map((item) => {
          let label = "";
          switch (this.language) {
            case "chinese":
              label = item.countryName;
              break;
            case "english":
              label = item.countryNameUS;
              break;
            case "russia":
              label = item.countryNameRU;
              break;
            case "spanish":
              label = item.countryNameES;
              break;
          }
          return {
            value: item.countryId,
            label: label,
          };
        });
      });
    },
    /** 查询区域列表 */
    getList() {
      console.log("查詢參數", this.queryParams);
      this.loading = true;
      listQuotation(this.queryParams)
        .then((response) => {
          this.quotationList = response.rows;
          this.queryParams.total = response.total;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.quotationNo = null;
      this.queryParams.projectName = null;
      this.queryParams.type = [];
      this.queryParams.segmentedMarket = [];
      this.queryParams.countryId = [];
      this.queryParams.city = null;
      this.queryParams.currencyId = [];
      this.queryParams.elevatorMode = null;
      this.queryParams.nickName = null;
      this.queryParams.createTime = [];
      this.queryParams.quotationStatus = [];
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = 10;

      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$tab.openPage(this.$t("quotation.add"), "/quotation/editQuotation", {
        type: "add",
      });
    },
    handleBargain(row, caseId) {
      console.log("报价id", row);
      switch (caseId) {
        case 0:
          // 议价
          this.$tab.openPage(
            this.$t("quotation.view"),
            "/quotation/editQuotation",
            {type: "bargain", quotationId: row.id}
          );
          break;
        case 1:
          // 议价审批
          this.$tab.openPage(
            this.$t("quotation.view"),
            "/quotation/editQuotation",
            {type: "bargainApproval", quotationId: row.id}
          );
          break;
        case 2:
          // 议价确认
          this.$tab.openPage(
            this.$t("quotation.view"),
            "/quotation/editQuotation",
            {type: "bargainConfirm", quotationId: row.id}
          );
          break;
      }
    },
    handleView(row, caseId) {
      console.log("报价id", row);
      switch (caseId) {
        case 0:
          // 查看
          this.$tab.openPage(
            this.$t("quotation.view"),
            "/quotation/editQuotation",
            {type: "view", quotationId: row.id}
          );
          break;
        case 1:
          // 技术评审
          this.$tab.openPage(
            this.$t("quotation.techReview"),
            "/quotation/editQuotation",
            {type: "techReview", quotationId: row.id}
          );
          break;
        case 2:
          // 采购询价
          this.$tab.openPage(
            this.$t("quotation.buyerInquiry"),
            "/quotation/editQuotation",
            {type: "buyerInquiry", quotationId: row.id}
          );
          break;
        case 3:
          // 财务询价
          this.$tab.openPage(
            this.$t("quotation.treasureInquiry"),
            "/quotation/editQuotation",
            {type: "treasureInquiry", quotationId: row.id}
          );
          break;
        case 4:
          // 销售确认
          this.$tab.openPage(
            this.$t("quotation.salesConfirm"),
            "/quotation/editQuotation",
            {type: "salesConfirm", quotationId: row.id}
          );
          break;
      }
    },
    handleDetail(row) {
      console.log("报价id", row);
      this.$tab.openPage(
        this.$t("quotation.view"),
        "/quotation/quotationDetail",
        {type: "view", quotationId: row.id}
      );
    },
    handleUpdate(row) {
      this.$tab.openPage(
        this.$t("quotation.edit"),
        "/quotation/editQuotation",
        {type: "edit", quotationId: row.id}
      );
    },
    handleOperateHistory(row) {
      this.$tab.openPage(
        this.$t("quotation.operateHistory"),
        "/quotation/operateHistory",
        {}
      );
    },
    /** 导出按钮操作 */
    handleExport() {
      let param = {
        ...this.queryParams,
      }
      param.pageNum = null
      param.pageSize = null
      console.log('导出参数', param)
      let fileName = this.$t('quotation.quotation') + parseTime(new Date(), '{y}{m}{d}') + '.xlsx'
      this.download("/business/quotation/export", param, fileName);
    },
    quotationIn(row, quotationList) {
      return quotationList.indexOf(row.quotationStatus) !== -1
    },
    quotationNotIn(row, quotationList) {
      return quotationList.indexOf(row.quotationStatus) === -1
    },
  },
};
</script>

<!--style-->
<style scoped>
::v-deep .el-dialog__body {
  padding-bottom: 0px;
}

.w-100 {
  width: 100%;
}

.mb16 {
  margin-bottom: 16px;
}

.ml20 {
  margin-left: 20px;
}

.card-title {
  font-family: Arial, Arial;
  font-size: 16px;
  font-weight: bold;
  color: rgba(0, 0, 0, 0.85);
  line-height: 18px;
}
</style>
