<template>
  <div class="app-container">
    <div class="account-title" style="margin-bottom: 16px;align-items: center;display: flex;width:97.6vw">
      {{ caseId == 0 ? $t('quotation.buyerQuotation') : $t("quotation.treasureQuotation") }}
      <div style="margin-left: auto;">
        <!--        采购报价确认-->
        <el-button type="primary" icon="el-icon-circle-check" @click="buyerConfirm" v-if="caseId == 0">{{ $t('common.confirm') }}</el-button>
        <!--        财务报价确认-->
        <el-button type="primary" icon="el-icon-circle-check" @click="treasurerConfirm" v-if="caseId == 1">{{ $t('common.confirm') }}</el-button>
        <!--        返回-->
        <el-button @click="cancel()" icon="el-icon-remove-outline">{{ $t('common.cancel') }}</el-button>
      </div>
    </div>
    <card-table :loading="loading" :modalData="reviewResultList" :searchParams="queryParams"
                labelWidth="120px" @pagination="getList" :max-height="600">
      <template #operations="{ selections }">
        <el-form class="account-form" :model="reviewForm">
          <el-row :gutter="20">
            <el-col :span="8">
              <!-- 电梯类型 -->
              <el-form-item :label="$t('paraLibrary.elevatorType')" prop="elevatorType">
                <el-select :disabled="true" v-model="reviewForm.elevatorType" style="width:20vw;">
                  <el-option v-for="item in dict.type.elevator_type" :key="item.value"
                             :label="item.label" :value="item.value"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <!--电梯型号 -->
              <el-form-item :label="$t('elevatorModel.elevatorModel')" prop="elevatorModelId">
                <el-select :disabled="true" v-model="reviewForm.elevatorModelId" style="width:20vw;">
                  <el-option v-for="dict in allElevatorModelList" :key="Number(dict.value)"
                             :label="dict.label" :value="Number(dict.value)"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <!--数量 -->
              <el-form-item :label="$t('quotation.count')" prop="elevatorNumber">
                <el-input :disabled="true" v-model="reviewForm.elevatorNumber" style="width:20vw;">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </template>
      <template #default="{ list }">
        <el-table-column align="center" type="index" label="No." width="55"/>
        <!--评审项目-->
        <Column :label="$t('quotation.reviewProject')" prop="markupName" :min-width="200"/>
        <!--关联参数信息-->
        <Column :label="$t('quotation.relatedParamInfo')" prop="relatedParaInfo" :min-width="300" searchType="dateRange"/>
        <!--系统评审结果-->
        <Column :label="$t('quotation.systemReviewResult')" prop="systemCheckResult" :min-width="140">
          <template #default="{ row }">
            <span v-if="row.systemCheckResult === '00'" style="color: #218AFC">{{ convertCheckResult(row.systemCheckResult) }}</span>
            <span v-else style="color: #D71943">{{ convertCheckResult(row.systemCheckResult) }}</span>
          </template>
        </Column>
        <!--理由-->
        <Column :label="$t('quotation.reason')" prop="nonStandardReason" :min-width="300">
          <template #default="{ row }">
            <span v-if="row.nonStandardReason" style="color: #D71943">{{ row.nonStandardReason }}</span>
            <span v-else>-</span>
          </template>
        </Column>
        <!--            附件-->
        <Column prop="solution" :label="$t('common.annex')" :min-width="200">
          <template #default="{ row }">
                <span v-if="row.fileList && row.fileList.length > 0">
                  <span v-for="(item, index)  in row.fileList">
                    <a :href="baseApi + item.filePath" :download="item.realFileName" style="color: #218AFC;text-decoration: underline">{{ item.realFileName }}</a>
                    <span v-if="index !== row.fileList.length - 1">，</span>
                  </span>
                </span>
            <span v-else>-</span>
          </template>
        </Column>
        <!--            数量-->
        <Column prop="quantity" :label="$t('quotation.count')" :min-width="80">
          <template #default="{ row }">
            <span v-if="row.quantity">{{ row.quantity }}</span>
            <span v-else>-</span>
          </template>
        </Column>
        <!--            单位-->
        <Column prop="unit" :label="$t('quotation.unit')" :min-width="80">
          <template #default="{ row }">
            <span v-if="row.unit">{{ row.unit }}</span>
            <span v-else>-</span>
          </template>
        </Column>
        <!--            技术意见（电气）-->
        <Column prop="solution" :label="$t('quotation.techAdvice') + '('+$t('quotation.electric')+')'" :min-width="300">
          <template #default="{ row }">
            <span v-if="row.solution">{{ row.solution }}</span>
            <span v-else>-</span>
          </template>
        </Column>
        <!--            技术意见（机械）-->
        <Column prop="solutionMachine" :label="$t('quotation.techAdvice') + '('+$t('quotation.machine')+')'" :min-width="300">
          <template #default="{ row }">
            <span v-if="row.solutionMachine">{{ row.solutionMachine }}</span>
            <span v-else>-</span>
          </template>
        </Column>
        <!--            采购价格(电气)-->
        <Column prop="buyerPrice" :label="$t('quotation.unitPrice') + '('+$t('quotation.electric')+')'" :min-width="caseId == 0?250:120" align="right">
          <template #default="{ row }">
                <span v-if="row.quotationFlagElectric == '1'">
                  <el-input-number v-model="row.buyerPrice" :min="-99999999" :precision="0" :max="99999999" :step="1" v-if="caseId == 0" :controls="false"
                                   :placeholder="$t('common.pleaseInput') + $t('quotation.unitPrice')" @change="unitPriceChange(row)"></el-input-number>
                  <span v-else>{{ numFormat(row.buyerPrice) }}</span>
                </span>
            <span v-else>-</span>
          </template>
        </Column>
        <!--            采购价格(机械)-->
        <Column prop="buyerPriceMachine" :label="$t('quotation.unitPrice') + '('+$t('quotation.machine')+')'" :min-width="caseId == 0?250:120" align="right">
          <template #default="{ row }">
                <span v-if="row.quotationFlagMachine == '1'">
                  <el-input-number v-model="row.buyerPriceMachine" :min="-99999999" :precision="0" :max="99999999" :step="1" v-if="caseId == 0" :controls="false"
                                   :placeholder="$t('common.pleaseInput') + $t('quotation.unitPrice')" @change="unitPriceChange(row)"></el-input-number>
                  <span v-else>{{ numFormat(row.buyerPriceMachine) }}</span>
                </span>
            <span v-else>-</span>
          </template>
        </Column>

        <!--            财务价格上浮（电气）-->
        <el-table-column prop="floatPercent" :label="$t('quotation.floatPercent') + '('+$t('quotation.electric')+')'" :min-width="280" v-if="caseId == 1">
          <template #default="{ row }">
                 <span v-if="row.quotationFlagElectric == '1'">
                  <el-input-number v-model="row.floatPercent" :controls="false" :precision="0" :min="0" :max="999999"
                                   :placeholder="$t('common.pleaseInput') + $t('quotation.floatPercent')" @change="floatPercentChange(row)"></el-input-number>
                </span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <!--            财务价格上浮（机械）-->
        <el-table-column prop="floatPercentMachine" :label="$t('quotation.floatPercent') + '('+$t('quotation.machine')+')'" :min-width="280" v-if="caseId == 1">
          <template #default="{ row }">
                <span v-if="row.quotationFlagMachine == '1'">
                  <el-input-number v-model="row.floatPercentMachine" :controls="false" :precision="0" :min="0" :max="999999"
                                   :placeholder="$t('common.pleaseInput') + $t('quotation.floatPercent')" @change="floatPercentChange(row)"></el-input-number>
                </span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <!--            财务报价(电气)-->
        <el-table-column prop="treasurerPrice" :label="$t('quotation.treasurerPrice') + '('+$t('quotation.electric')+')'" :min-width="200" v-if="caseId == 1" align="right">
          <template #default="{ row }">
            {{ numFormat(row.treasurerPrice) }}
          </template>
        </el-table-column>
        <!--            财务报价(机械)-->
        <el-table-column prop="treasurerPriceMachine" :label="$t('quotation.treasurerPrice') + '('+$t('quotation.machine')+')'" :min-width="200" v-if="caseId == 1" align="right">
          <template #default="{ row }">
            {{ numFormat(row.treasurerPriceMachine) }}
          </template>
        </el-table-column>
        <!--            总计-->
        <Column prop="total" :label="$t('quotation.totalPrice')" :min-width="200" align="right">
          <template #default="{ row }">
            {{ numFormat(row.total) }}
          </template>
        </Column>

      </template>
    </card-table>
  </div>
</template>

<script>
import Column from "@/components/element/table/Column.vue";
import {mapGetters} from "vuex";
import {listAllPriceDetail} from "@/api/business/quotation/priceDetail";

export default {
  name: "BuyerTreasurerQuotation",
  inject: ["main"],
  components: {Column},
  dicts: [
    "elevator_type",
    "system_check_result",
  ],
  data() {
    return {
      // 下载文件url前缀
      baseApi: process.env.VUE_APP_BASE_API,
      // 采购报价 0  财务报价 1
      caseId: null,
      // 电梯规格Id
      specificationId: null,
      elevatorType: null,
      elevatorModelId: null,
      elevatorNumber: null,
      // 页面表单
      reviewForm: {
        elevatorType: null,
        elevatorModelId: null,
        elevatorNumber: null,
      },
      allElevatorModelList: [],
      // 遮罩层
      loading: true,
      // 非多个禁用
      multiple: true,
      single: true,
      ids: [],
      // 显示搜索条件
      showSearch: true,
      // 报价列表
      reviewResultList: [],
      language: null,
      queryParams: {
        total: 0
      }
    };
  },
  async created() {
    this.caseId = this.$route.query && this.$route.query.caseId;
    this.specificationId = this.$route.query && this.$route.query.specificationId;
    this.elevatorType = this.$route.query && this.$route.query.elevatorType;
    this.elevatorModelId = this.$route.query && this.$route.query.elevatorModelId;
    this.elevatorNumber = this.$route.query && this.$route.query.elevatorNumber;
    this.reviewForm = {
      elevatorType: this.elevatorType,
      elevatorModelId: Number(this.elevatorModelId),
      elevatorNumber: this.elevatorNumber,
    }
    this.language = this.$i18n.locale;
    await this.initElevatorModel();
    await this.getList();
  },
  computed: {
    ...mapGetters(["userId"]),
    localLabelSuffix() {
      return labelSuffix[this.$i18n.locale] || "";
    },
  },
  async activated() {
  },
  methods: {
    // 采购弹窗报价修改联动
    unitPriceChange(row) {
      let buyerPrice = row.buyerPrice ? row.buyerPrice : 0;
      let buyerPriceMachine = row.buyerPriceMachine ? row.buyerPriceMachine : 0;

      if (row.buyerPrice || row.buyerPriceMachine) {
        let quantity = row.quantity
        if (quantity == null) {
          quantity = 1
        }
        row.total = (buyerPrice + buyerPriceMachine) * quantity.toFixed(0)
      } else {
        row.total = '-'
      }
    },
    // 采购报价确认
    buyerConfirm() {
      // 采购单价未设置
      for (let i = 0; i < this.reviewResultList.length; i++) {
        if (this.reviewResultList[i].quotationFlagElectric == '1' && this.reviewResultList[i].buyerPrice === undefined) {
          this.$message.error(this.$t('quotation.setSalesPrice') + '(' + this.$t('quotation.electric') + ')')
          return
        }
        if (this.reviewResultList[i].quotationFlagMachine == '1' && this.reviewResultList[i].buyerPriceMachine === undefined) {
          this.$message.error(this.$t('quotation.setSalesPrice') + '(' + this.$t('quotation.machine') + ')')
          return
        }
      }
      let data = {
        id: this.specificationId,
        data: this.reviewResultList
      }
      store.commit('ADD_BUYER_REVIEW', data)
      this.$message.success(this.$t('common.operateSuccess'))
      this.$tab.closePage();
    },
    // 财务报价确认
    treasurerConfirm() {
      // 财务上浮未设置
      for (let i = 0; i < this.reviewResultList.length; i++) {
        if (this.reviewResultList[i].quotationFlagElectric == '1' && this.reviewResultList[i].floatPercent === undefined) {
          this.$message.error(this.$t('quotation.setTreasurePriceRate') + '(' + this.$t('quotation.electric') + ')')
          return
        }
        if (this.reviewResultList[i].quotationFlagMachine == '1' && this.reviewResultList[i].floatPercentMachine === undefined) {
          this.$message.error(this.$t('quotation.setTreasurePriceRate') + '(' + this.$t('quotation.machine') + ')')
          return
        }
      }
      let data = {
        id: this.specificationId,
        data: this.reviewResultList
      }
      store.commit('ADD_TREASURER_REVIEW', data)
      this.$message.success(this.$t('common.operateSuccess'))
      this.$tab.closePage();
    },
    // 梯形初始化
    async initElevatorModel() {
      let form = {
        needAll: true
      }
      const response = await listModelNewAll(form);
      if (response.rows) {
        response.rows.forEach(item => {
          this.allElevatorModelList.push(
            {
              'label': item.elevatorModel,
              'value': item.id,
            }
          )
        })
      }
    },
    /** 查询区域列表 */
    getList() {
      this.loading = true
      this.reviewResultList = []
      // 优先从缓存获取
      let cacheList = undefined
      if (this.caseId == 0) {
        cacheList = this.$store.state.elevators.buyerQuotationObj[this.specificationId]
      } else {
        cacheList = this.$store.state.elevators.treasurerQuotationObj[this.specificationId]
      }

      if (cacheList) {
        console.log('从缓存获取', cacheList)
        this.reviewResultList = JSON.parse(JSON.stringify(cacheList));
        this.queryParams.total = 0
        this.loading = false
      } else {
        console.log('从后端获取', cacheList)
        let form = {
          specificationId: this.specificationId,
          systemCheckResult: '01',
        }
        listAllPriceDetail(form).then(response => {
          let list = response.rows
          if (list && list.length > 0) {
            for (let i = 0; i < list.length; i++) {
              list[i].elevatorNumber = this.elevatorNumber
              if (this.caseId == 1) {
                if (!list[i].floatPercent) {
                  list[i].floatPercent = undefined
                }
                if (!list[i].floatPercentMachine) {
                  list[i].floatPercentMachine = undefined
                }
                // 财务报价初始化处理
                this.floatPercentChange(list[i])
              } else {
                // 采购报价初始化处理
                if (!list[i].buyerPrice) {
                  list[i].buyerPrice = undefined
                }
                if (!list[i].buyerPriceMachine) {
                  list[i].buyerPriceMachine = undefined
                }
              }
            }
          }
          this.reviewResultList = list
          this.queryParams.total = 0
          this.loading = false
        })
      }
    },
    // 价格上浮& 修改联动
    floatPercentChange(row) {
      let quantity = row.quantity
      if (quantity == null) {
        quantity = 1
      }
      // 电气报价
      let one = 0
      if (row.quotationFlagElectric == '1') {
        if (row.floatPercent) {
          row.treasurerPrice = (row.buyerPrice * (row.floatPercent / 100 + 1)).toFixed(0)
        } else {
          row.treasurerPrice = row.buyerPrice
        }
        one = row.treasurerPrice
      }

      // 机械报价
      let two = 0
      if (row.quotationFlagMachine == '1') {
        if (row.floatPercentMachine) {
          row.treasurerPriceMachine = (row.buyerPriceMachine * (row.floatPercentMachine / 100 + 1)).toFixed(0)
        } else {
          row.treasurerPriceMachine = row.buyerPriceMachine
        }
        two = row.treasurerPriceMachine
      }
      console.log('-------------------')
      console.log(one)
      console.log(two)
      console.log(quantity)
      row.total = ((Number(two) + Number(one)) * quantity).toFixed(0)

      console.log(row.total)
    },
    convertCheckResult(status) {
      if (!status) return '-'
      const check = this.dict.type.system_check_result.filter(item => item.value == status)
      if (check && check.length > 0) {
        return check[0].label
      } else {
        return '-'
      }
    },
    cancel() {
      this.$tab.closePage();
    },
  },
};

import {listModelNewAll} from "@/api/business/crm/elevatorModel";
import store from "@/store";

const labelSuffix = {
  chinese: "",
  english: "US",
  russia: "RU",
  spanish: "ES",
};
</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;
}

.app-container {
  padding: 16px 1vw;
}

.account-title {
  font-family: Arial, Arial;
  font-weight: bold;
  font-size: 18px;
  line-height: 21px;
}

.el-input-number ::v-deep .el-input__inner {
  text-align: left;
}
</style>
