<template>
  <div class="app-container">
    <div class="account-title" style="margin-bottom: 16px;align-items: center;display: flex;width:97.6vw">
      {{ reviewCaseFlag ? $t("quotation.systemReviewResult") : $t("quotation.techReview") }}
      <div style="margin-left: auto;">
        <!--        确认-->
        <el-button type="primary" icon="el-icon-circle-check" @click="techReviewConfirm" v-if="!reviewCaseFlag">{{ $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" :showSearch="true" searchType="select" :searchDict="dict.type.system_check_result">
          <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" v-if="!reviewCaseFlag">
          <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="solution" :label="$t('quotation.category')" :min-width="180" v-if="!reviewCaseFlag && false">
          <template #default="{ row }">
            <el-checkbox v-model="row.quotationFlagElectric" :true-label="1" :false-label="0" class="para-checkbox">
              <span style="font-weight: normal;line-height: 36px;font-size: 14px;color:#606266">{{ $t('quotation.electric') }}</span>
            </el-checkbox>
            <el-checkbox v-model="row.quotationFlagMachine" :true-label="1" :false-label="0" class="para-checkbox">
              <span style="font-weight: normal;line-height: 36px;font-size: 14px;color:#606266">{{ $t('quotation.machine') }}</span>
            </el-checkbox>
          </template>
        </Column>
        <!--            技术意见（电气）-->
        <Column prop="solution" :label="$t('quotation.techAdvice') + '('+$t('quotation.electric')+')'" :min-width="400" v-if="!reviewCaseFlag">
          <template #default="{ row }">
            <!--                <el-tooltip :content="row.solution" placement="top">-->
            <el-input v-if="row.systemCheckResult === '01' && flowStatus == '101'" v-model="row.solution" type="textarea" rows="2" show-word-limit
                      :placeholder="$t('common.pleaseInput') + $t('quotation.techAdvice')" maxlength="500"></el-input>
            <span v-else>
                  <span v-if="row.solution"> {{ row.solution }} </span>
                  <span v-else>-</span>
                </span>
            <!--                </el-tooltip>-->
          </template>
        </Column>
        <!--            采购价格(电气)-->
        <Column prop="buyerPrice" :label="$t('quotation.unitPrice') + '('+$t('quotation.electric')+')'" :min-width="250" align="right" v-if="!reviewCaseFlag">
          <template #default="{ row }">
                <span v-if="row.quotationFlagElectric == '1'">
                  <el-input-number v-model="row.buyerPrice" :min="-99999999" :precision="0" :max="99999999" :step="1" :controls="false" v-if="row.systemCheckResult === '01' && flowStatus == '101'"
                                   :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="solution" :label="$t('quotation.techAdvice') + '('+$t('quotation.machine')+')'" :min-width="400" v-if="!reviewCaseFlag && flowStatus == '105'">
          <template #default="{ row }">
            <!--                <el-tooltip :content="row.solution" placement="top">-->
            <el-input v-if="row.systemCheckResult === '01' && flowStatus == '105'" v-model="row.solutionMachine" type="textarea" rows="2" show-word-limit
                      :placeholder="$t('common.pleaseInput') + $t('quotation.techAdvice')" maxlength="500"></el-input>
            <span v-else>{{ row.solutionMachine }}</span>
            <!--                </el-tooltip>-->
          </template>
        </Column>

        <!--            采购价格(机械)-->
        <Column prop="buyerPriceMachine" :label="$t('quotation.unitPrice') + '('+$t('quotation.machine')+')'" :min-width="250" align="right" v-if="!reviewCaseFlag && flowStatus == '105'">
          <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="row.systemCheckResult === '01' && flowStatus == '105'" :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>

      </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";
import {listModelNewAll} from "@/api/business/crm/elevatorModel";
import store from "@/store";

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

export default {
  name: "TechReview",
  inject: ["main"],
  components: {Column},
  dicts: [
    "elevator_type",
    "system_check_result",
  ],
  data() {
    return {
      // 当前报价节点状态
      flowStatus: null,
      // 系统评审：true 技术评审：false
      reviewCaseFlag: true,
      // 电梯规格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: [],
      // 下载文件url前缀
      baseApi: process.env.VUE_APP_BASE_API,
      // 完整报价列表
      allReviewResultList: [],
      language: null,
      queryParams: {
        total: 0
      }
    };
  },
  async created() {
    this.flowStatus = this.$route.query && this.$route.query.flowStatus;
    this.reviewCaseFlag = this.$route.query && (this.$route.query.reviewCaseFlag == 'true');
    console.log('reviewCaseFlag', this.reviewCaseFlag)
    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() {
  },
  watch: {
    'queryParams.systemCheckResult'(newValue, oldValue) {
      this.syncData()
      if (newValue){
        console.log('部分展示')
        this.reviewResultList = this.allReviewResultList.filter(item=> item.systemCheckResult == newValue)
      }else {
        console.log('全部展示')
        this.reviewResultList = this.allReviewResultList
      }
    }
  },
  methods: {
    // 同步数据
    syncData(){
      for (let i = 0; i < this.reviewResultList; i++) {
        for (let j = 0; j < this.allReviewResultList; j++) {
          if (this.allReviewResultList[j].id === this.reviewResultList[i].id){
            this.allReviewResultList[j].solution = this.reviewResultList[i].solution
            this.allReviewResultList[j].solutionMachine = this.reviewResultList[i].solutionMachine
            this.allReviewResultList[j].buyerPrice = this.reviewResultList[i].buyerPrice
            this.allReviewResultList[j].buyerPriceMachine = this.reviewResultList[i].buyerPriceMachine
            break
          }
        }
      }
    },
    // 技术评审确认
    techReviewConfirm() {
      this.syncData()

      // 采购单价未设置
      for (let i = 0; i < this.reviewResultList.length; i++) {
        if (this.flowStatus == '101' && this.reviewResultList[i].quotationFlagElectric == '1' && this.reviewResultList[i].buyerPrice !==0 && !this.reviewResultList[i].buyerPrice) {
          this.$message.error(this.$t('quotation.setSalesPrice') + '(' + this.$t('quotation.electric') + ')')
          return
        }
        if (this.flowStatus == '105' && this.reviewResultList[i].quotationFlagMachine == '1' && this.reviewResultList[i].buyerPriceMachine !==0 && !this.reviewResultList[i].buyerPriceMachine) {
          this.$message.error(this.$t('quotation.setSalesPrice') + '(' + this.$t('quotation.machine') + ')')
          return
        }
      }

      let data = {
        id: this.specificationId,
        data: this.allReviewResultList
      }
      store.commit('ADD_TECH_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,
            }
          )
        })
      }
    },
    // 采购弹窗报价修改联动
    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 = '-'
      }
    },
    /** 查询区域列表 */
    getList() {
      this.loading = true
      this.reviewResultList = []
      // 优先从缓存获取
      let cacheList = this.$store.state.elevators.techReviewObj[this.specificationId]
      if (cacheList) {
        console.log('从缓存获取', cacheList)
        this.reviewResultList = JSON.parse(JSON.stringify(this.$store.state.elevators.techReviewObj[this.specificationId]));
        this.allReviewResultList = this.reviewResultList;
        this.queryParams.total = 0
        this.loading = false
      } else {
        console.log('从后端获取', cacheList)
        let form = {
          specificationId: this.specificationId
        }
        listAllPriceDetail(form).then(response => {
          response.rows.forEach(item => {
            if (item.buyerPrice === null) {
              item.buyerPrice = undefined
            }
            if (item.buyerPriceMachine === null) {
              item.buyerPriceMachine = undefined
            }
          })
          this.reviewResultList = response.rows
          this.allReviewResultList = response.rows
          this.queryParams.total = 0
          this.loading = false
        })
      }
    },
    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();
    },
  },
};
</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;
}
</style>
