<!--
  @description: 订单管理-行项目信息编辑
  @author: lxl
  @date： 2021-1-8 10:30:12
-->
<template>
  <div>
    <!-- 订单行项目信息 -->
    <section class="title title_border p0-16">
      <i class="iconfont icon-fanhui pointer" @click="back()" />
      收货处理编辑
    </section>
    <div class="p0-16">
      <!-- 订单基本信息 -->
      <procurementOrderBasicCompDetail
        :order-info-data="detailInfoData.orderInfoList"
      />
      <!-- 订单行项目信息 -->
      <template>
        <!-- <procurementOrderLineItemCompDetail
          :line-item-info-data="detailInfoData.lineItemInfoList"
          :currency="detailInfoData.currency"
        /> -->
        <div>
          <div class="clearfix offerInfo">
            <p class="fl page-title">
              2.行项目信息
            </p>
            <p class="fr mt10 tip-size">
              含税总价（元）：<span class="procurement_orange-color">{{ totalPrice }}</span>
              币种： <span class="procurement_orange-color">{{ filterDictText(protproject_currencyList,detailInfoData.currency) }}</span>
            </p>
          </div>
          <el-form ref="formData" :model="formData" :rules="formData.rules" :inline-message="true">
            <el-table
              :data="formData.lineItemInfoList"
              border
              class="clear-hint"
            >
              <el-table-column type="index" label="序号" width="55" align="center" />
              <el-table-column
                prop="lineItemNumber"
                header-align="center"
                align="center"
                min-width="180"
                label="行项目编号"
              />
              <el-table-column
                prop="productNo"
                header-align="center"
                align="center"
                min-width="150"
                label="物资编码"
              />
              <el-table-column
                prop="productDescribe"
                header-align="center"
                align="left"
                min-width="200"
                label="物资描述"
              />
              <el-table-column align="center" min-width="180" label="类别">
                <template slot-scope="scope">
                  <span> {{ filterDictText(plan_purchase_typeList, scope.row.productCategory) }}</span>
                </template>
              </el-table-column>
              <el-table-column
                header-align="center"
                min-width="260"
              >
                <template slot="header">
                  <span class="red-star">*</span>
                  <span>成交数量</span>
                </template>
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'lineItemInfoList.' + scope.$index + '.quantity'"
                    :rules="formData.rules.quantity"
                    class="noneMess"
                  >
                    <money :thousands="true" :unit-fixed="4" :width="'240px'" :money-value="scope.row" name="quantity" @input="onQuantity(scope.row,scope.$index)" />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                header-align="center"
                prop="unit"
                align="center"
                min-width="100"
                label="计量单位"
              >
                <template slot-scope="scope">
                  {{ filterDictText(purchaseUnitList, scope.row.unit) }}
                </template>
              </el-table-column>
              <el-table-column
                prop="taxRate"
                header-align="center"
                align="right"
                min-width="100"
                label="税率(%)"
              />
              <el-table-column
                header-align="center"
                min-width="260"
              >
                <template slot="header">
                  <span class="red-star">*</span>
                  <span>成交单价(元)</span>
                </template>
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'lineItemInfoList.' + scope.$index + '.transactionBudget'"
                    :rules="formData.rules.transactionBudget"
                    class="noneMess"
                  >
                    <money :thousands="true" :unit-fixed="2" :width="'240px'" :money-value="scope.row" name="transactionBudget" @input="getSummaries" />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                header-align="center"
                label="成交总价（元）"
                min-width="130"
                align="right"
              >
                <template slot-scope="scope">
                  <span>{{ scope.row.distributionTotalMoney?moneyFormat(scope.row.distributionTotalMoney.toFixed(2)):scope.row.distributionTotalMoney }}</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="offerRemarks"
                header-align="center"
                align="left"
                min-width="200"
                label="品牌/生产厂家"
              />
              <el-table-column
                align="center"
                label="交货日期"
                min-width="180"
              >
                <template slot-scope="scope">
                  {{ $Moment(scope.row.deliveryTime).format(momentDate) && scope.row.deliveryTime }}
                </template>
              </el-table-column>
              <el-table-column
                prop="deliveryAdress"
                align="left"
                header-align="center"
                min-width="220"
                label="交货地点"
              />
            </el-table>
          </el-form>
        </div>
        <pagination :pagination-data="paginationLineData" @change="getLineItemData" />
      </template>

      <!-- 订单发货信息 -->
      <template>
        <procurementOrderDeliverCompDetail
          :delivery-info-data="detailInfoData.deliveryInfoList"
        >
          <template slot-scope="scope">
            <el-link
              type="primary"
              @click.stop="viewReceipts(scope.row)"
            >
              [查看]
            </el-link>
          </template>
        </procurementOrderDeliverCompDetail>
        <pagination :pagination-data="paginationDeliverData" @change="getDeliveryData" />
      </template>

      <!-- 订单收款信息 -->
      <template>
        <procurementOrderCollectionCompDetail
          :collection-info-data="detailInfoData.collectionInfoList"
        >
          <!-- 收款表操作按钮 -->
          <template slot-scope="scope">
            <el-link
              type="primary"
              @click.stop="viewCollection(scope.row)"
            >
              [查看]
            </el-link>
          </template>
        </procurementOrderCollectionCompDetail>
        <pagination :pagination-data="paginationCollectionData" @change="getCollectionData" />
      </template>
    </div>
    <!--保存按钮-->
    <div class="but_footer">
      <div class="but_footer-h">
        <div class="but_footer-but">
          <!-- 保存 -->
          <el-button
            :loading="confirmLoading"
            @click="save('formData')"
          >
            保存
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
/*  api*/
import {
  queryProcurementOrderInfo, // 基本信息
  listProcurementOrderProductPages, // 行项目
  listSupplierProcurementSendGoodsPages, // 发货信息
  listSupplierConsigneeApplicationPages, // 收款信息
  updateProcurementOrderProduct // 保存
} from '@/api/procurement/procurementOrder'
/* 组件*/
import procurementOrderBasicCompDetail from '@/views/procurement/procurementOrder/procurementOrderInfo/procurementOrderBasicComp-detail.vue' // 订单的基本信息组件
import procurementOrderLineItemCompDetail from '@/views/procurement/procurementOrder/procurementOrderInfo/procurementOrderLineItemComp-detail.vue' // 订单行项目信息列表组件
import procurementOrderDeliverCompDetail from '@/views/procurement/procurementOrder/procurementOrderInfo/procurementOrderDeliverComp-detail.vue' // 订单发货列表组件
import procurementOrderCollectionCompDetail from '@/views/procurement/procurementOrder/procurementOrderInfo/procurementOrderCollectionComp-detail.vue' // 收款申请信息列表组件
/* 公用*/
import pagination from '@comp/common/pagination/pagination' // 分页组件
import { filterDictText, moneyFormat, cloneObject, totalHeadCount } from '@/assets/js/utils' // 字典code翻译中文
import money from '@comp/common/money/money' // 金币组件
import { characters1_auto } from '@/assets/js/validate'// 校验输入内容

/* mixins*/
import { procurementOrderGroupMixins } from '@/views/procurement/procurementOrder/mixins/procurementOrderGroupMixins.js'
import GXinput from '../../../../components/common/GXinput/GXinput.vue'

export default {
  name: 'LineItemUp',
  components: {
    procurementOrderLineItemCompDetail,
    procurementOrderBasicCompDetail,
    procurementOrderDeliverCompDetail,
    procurementOrderCollectionCompDetail,
    pagination,
    money,
    GXinput
  },
  mixins: [procurementOrderGroupMixins],
  data() {
    return {
      orderId: this.$route.params.orderId, // 订单id
      confirmLoading: false,
      detailInfoData: {
        orderInfoList: {}, // 订单基本信息
        deliveryInfoList: [], // 发货信息
        collectionInfoList: [], // 收款信息
        currency: '' // 币种
      },
      copyData: [], // 备份行项目
      index: '',
      formData: {
        lineItemInfoList: [], // 行项目信息
        rules: {
          transactionBudget: [
            { required: true, validator: characters1_auto, trigger: 'blur' } // 成交单价
          ],
          quantity: [
            { required: true, validator: characters1_auto, trigger: 'blur' } // 成交数量
          ]
        }
      },
      // 行项目分页信息
      paginationLineData: {
        pageNo: 1,
        pageSize: 10,
        total: 0
      },
      // 发货信息分页信息
      paginationDeliverData: {
        pageNo: 1,
        pageSize: 10,
        total: 0
      },
      // 收款信息行项目分页信息
      paginationCollectionData: {
        pageNo: 1,
        pageSize: 10,
        total: 0
      }
    }
  },
  computed: {
    // 计算总价
    totalPrice: function() {
      // 初始化数据
      const totalPriceData = []
      let totalPrice = 0
      this.formData.lineItemInfoList && this.formData.lineItemInfoList.map(cur => {
        // 判断单向总价是否是数值
        if (!isNaN(cur.distributionTotalMoney)) {
          // 将总价push到初始数据中
          totalPriceData.push(cur.distributionTotalMoney)
          // 调用公共求和方法
          totalPrice = totalHeadCount(totalPriceData).toFixed(2)
          return
        }
        totalPrice = 0
      })

      return totalPrice
    }
  },
  watch: {
    // 监听行项目表格页数，当变化时保存数据
    'paginationLineData.pageNo'(val) {
      this.save()
    }
  },
  created() {
    this.getBaseInfoData() // 基础信息
    this.getLineItemData() // 行项目信息
    this.getDeliveryData() // 发货信息
    this.getCollectionData() // 收款信息
  },
  methods: {
    filterDictText, // 字典
    moneyFormat, // 金额
    // 计算成交总价
    getSummaries() {
      this.formData.lineItemInfoList.forEach((item) => {
        if (item.transactionBudget && item.quantity) {
          item.distributionTotalMoney = Number(item.transactionBudget * item.quantity)
        } else {
          item.distributionTotalMoney = 0
        }
      })
    },
    // 成交数量
    onQuantity(row, index) {
      // 成交数量校验新填写数量不能大于原数量
      if (row.quantity > this.copyData[this.index].quantity) {
        this.$message.warning('成交数量不能大于原数量')
      }
      this.getSummaries()
    },
    // 收货详情
    viewReceipts(row) {
      this.$router.push({
        name: 'ProcurementOrderReceiveDetail',
        params: {
          goodsId: row.id,
          orderId: this.orderId
        }
      })
    },
    // 收款确认详情
    viewCollection(row) {
      this.$router.push({
        name: 'ProcurementOrderCollectionConfirmDetail',
        params: {
          conAppliId: row.id // 订单Id
        }
      })
    },
    // 基本信息
    getBaseInfoData() {
      const params = {
        orderId: this.orderId
      }
      queryProcurementOrderInfo(params).then((response) => {
        this.detailInfoData.orderInfoList = response.data
        this.detailInfoData.currency = response.data.currency
      })
    },
    // 获取行项目信息
    getLineItemData() {
      const params = {
        orderId: this.orderId,
        pageNo: this.paginationLineData.pageNo,
        pageSize: this.paginationLineData.pageSize
      }
      listProcurementOrderProductPages(params).then(response => {
        this.loading = false
        this.formData.lineItemInfoList = response.data.records
        this.copyData = cloneObject(response.data.records)
        this.paginationLineData.total = response.data.total
      }).catch(() => {
      })
    },
    // 获取发货信息
    getDeliveryData() {
      const params = {
        orderId: this.orderId,
        pageNo: this.paginationDeliverData.pageNo,
        pageSize: this.paginationDeliverData.pageSize
      }
      listSupplierProcurementSendGoodsPages(params).then(response => {
        this.loading = false
        this.detailInfoData.deliveryInfoList = response.data.records
        this.paginationDeliverData.total = response.data.total
      }).catch(() => {
      })
    },
    // 收款信息
    getCollectionData() {
      const params = {
        orderId: this.orderId,
        pageNo: this.paginationCollectionData.pageNo,
        pageSize: this.paginationCollectionData.pageSize
      }
      listSupplierConsigneeApplicationPages(params).then(response => {
        this.loading = false
        this.detailInfoData.collectionInfoList = response.data.records
        this.paginationCollectionData.total = response.data.total
      }).catch(() => {
      })
    },
    back() {
      this.$router.push({
        path: '/procurement/procurementOrderQueryList'
      })
    },
    // 成交数量校验新填写数量不能大于原数量
    quantityFlag() {
      let flag = true
      this.formData.lineItemInfoList.forEach((item, index) => {
        if (item.quantity > this.copyData[index].quantity) {
          flag = false
        }
      })
      return flag
    },
    // 保存
    save(formName) {
      this.$refs[formName].validate((valid, field) => {
        // 判断成交数量
        if (!this.quantityFlag()) {
          this.$message.warning('成交数量不能大于原数量')
          return false
        }
        if (valid) {
          this.confirmLoading = true
          const data = this.formData.lineItemInfoList.map((item) => {
            return {
              id: item.id,
              orderId: item.orderId,
              distributionNumber: item.distributionNumber,
              distributionTotalMoney: item.distributionTotalMoney,
              transactionBudget: item.transactionBudget
            }
          })
          const params = {
            orderProList: data
          }
          updateProcurementOrderProduct(params).then((res) => {
            this.confirmLoading = false
            this.back()
          })
        } else {
          this.confirmLoading = false
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.clear-hint{
  /deep/.el-form-item--small .el-form-item__error {
    display: none;
  }
  /deep/ .el-form-item.el-form-item--small {
    margin-bottom: 0px;
  }
}
</style>
