<template>
  <div v-loading="isLoading">
    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-position="top" label-width="120px" class="rule-form-orange">
      <cy-info-title>基础信息（下游结算）</cy-info-title>
      <el-form-item label="项目名称" prop="businessNumber" required>
        <el-input v-model="ruleForm.businessName" disabled />
      </el-form-item>
      <el-form-item label="核心企业名称">
        <el-input v-model="ruleForm.customer.corporateName" disabled />
      </el-form-item>
      <el-form-item label="供应商（主体）名称">
        <el-input v-model="ruleForm.supplier.corporateName" disabled />
      </el-form-item>
      <el-form-item label="贸易平台">
        <el-input v-model="ruleForm.platform.platformName" disabled />
      </el-form-item>
      <el-form-item label="业务编号">
        <el-input v-model="ruleForm.businessNumber" disabled />
      </el-form-item>
      <el-form-item label="结算日期" prop="settlementDate" required>
        <el-date-picker  v-model="ruleForm.settlementDate" value-format="yyyy-MM-dd" type="date" placeholder="选择结算日期" style="width: 100%;" disabled />
      </el-form-item>
      <el-form-item label="结算金额" prop="settlementAmount" required>
        <el-input v-model="ruleForm.settlementAmount" placeholder="请输入结算金额" disabled />
      </el-form-item>
      <el-form-item label="经办人（供应商）" prop="operatorSupplier" required>
        <el-input v-model="ruleForm.operatorSupplier" placeholder="请输入经办人（供应商）" disabled />
      </el-form-item>
      <el-form-item label="经办人（核心企业）" prop="operatorEnterprise" required>
        <el-input v-model="ruleForm.operatorEnterprise" placeholder="请输入经办人（核心企业）" disabled />
      </el-form-item>
      <cy-info-title style="margin-top: 15px;">货物信息（下游结算）
        <span style="font-size: 12px; color: #A3A8AC;">单位：元</span>
        <!-- <b v-show="ruleForm.countTheGoods" style="margin: 0 20px; color: #FF0000;">数量合计：{{ changeNum1 }}</b>
        <b v-show="ruleForm.settleTotalSalesPrice" style="color: #FF0000;">销售总价合计：{{ changeNum2 }}</b>
        <b v-show="buyTotalPrice" style="margin-left: 20px; color: #FF0000;">采购总价合计：{{ changeNum3 }}</b> -->
      </cy-info-title>
      <div style="width: 100%; margin-bottom: 20px;">
        <el-table :data="goodsList" style="width: 100%;">
          <el-table-column type="index" label="序号" show-overflow-tooltip/>
          <el-table-column prop="acceptanceGoodsNumber" label="验收单号" show-overflow-tooltip/>
          <el-table-column prop="acceptanceDate" label="验收日期" show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ scope.row.acceptanceDate ? scope.row.acceptanceDate.split(' ')[0] : '' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="goodsName" label="货物名称" show-overflow-tooltip/>
          <el-table-column prop="goodsFactory" label="厂家" show-overflow-tooltip/>
          <el-table-column prop="goodsType" label="型号" show-overflow-tooltip/>
          <el-table-column prop="goodsUnit" label="单位" show-overflow-tooltip/>
          <el-table-column prop="goodsQuantity" label="数量" show-overflow-tooltip/>
          <el-table-column prop="referencePrice" label="参考价格" show-overflow-tooltip/>
          <el-table-column prop="floatingPrice" label="浮动价格" show-overflow-tooltip/>
          <el-table-column prop="salesPrice" label="销售单价" show-overflow-tooltip/>
          <el-table-column prop="salesTotalPrice" label="销售总价" show-overflow-tooltip/>
          <el-table-column prop="salesGuaranteeMoney" label="销售质保金" show-overflow-tooltip/>
          <el-table-column prop="purchasePrice" label="采购单价" show-overflow-tooltip/>
          <el-table-column prop="purchaseTotalPrice" label="采购总价" show-overflow-tooltip/>
          <el-table-column prop="purchaseGuaranteeMoney" label="采购质保金" show-overflow-tooltip/>
        </el-table>
        <div style="margin-top: 10px;">
          <b v-show="ruleForm.countTheGoods" style="margin: 0 20px; color: #FF0000;">数量合计：{{ changeNum1 }}</b>
          <b v-show="ruleForm.settleTotalSalesPrice" style="color: #FF0000;">销售总价合计：{{ changeNum2 }}</b>
          <b v-show="buyTotalPrice" style="margin-left: 20px; color: #FF0000;">采购总价合计：{{ changeNum3 }}</b>
        </div>
      </div>
      <cy-info-title>对账区间</cy-info-title>
      <el-form-item label="开始日期" prop="settlementStartDate" required>
        <el-date-picker v-model="ruleForm.settlementStartDate" value-format="yyyy-MM-dd" type="date" placeholder="选择开始日期" style="width: 100%;" disabled />
      </el-form-item>
      <el-form-item label="结束日期" prop="settlementEndDate" required>
        <el-date-picker v-model="ruleForm.settlementEndDate" value-format="yyyy-MM-dd" type="date" placeholder="选择结束日期" style="width: 100%;" disabled />
      </el-form-item>
      <template v-if="ruleForm.repayList && ruleForm.repayList.length > 0">
        <cy-info-title style="margin-top: 15px;">回款计划</cy-info-title>
        <div style="width: 100%; margin-bottom: 20px;">
          <el-table :data="ruleForm.repayList" style="width: 100%;">
            <el-table-column type="index" label="编号" show-overflow-tooltip/>
            <el-table-column prop="repaymentDate" label="回款日期" show-overflow-tooltip>
              <template slot-scope="scope">
                <span>{{ scope.row.repaymentDate ? scope.row.repaymentDate.split(' ')[0] : '' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="repaymentAmount" label="回款金额（元）" show-overflow-tooltip>
            </el-table-column>
          </el-table>
          <div style="margin-top: 10px;">
            <b v-show="repayTotalNum" style="margin: 0 20px; color: #FF0000;">合计：{{ repayTotalNum }}</b>
          </div>
        </div>
      </template>
      <cy-info-title>结算文件（下游）</cy-info-title>
      <el-form-item label="下游结算清单附件" prop="newfileIds" required>
        <cy-upload
          ref="fileStorage1"
          :upload-params="{ mouldName: 'settlementFile' }"
          :file-data="ruleForm.fileIds"
          :upload-from-orange-status="true"
          placeholder="请上传网价附件" disabled
        />
      </el-form-item>
      <el-form-item label="结算货物数量（总）" prop="countTheGoods">
        <el-input v-model="ruleForm.countTheGoods" disabled />
      </el-form-item>
      <el-form-item label="结算销售总价" prop="settleTotalSalesPrice">
        <el-input v-model="ruleForm.settleTotalSalesPrice" disabled />
      </el-form-item>
      <cy-info-title style="margin-top: 15px;">上传网价附件</cy-info-title>
      <el-form-item label="附件：" prop="newnetPriceFileIds" style="width: 100%; margin-right: 0;">
        <cy-upload
          ref="fileStorage2"
          :upload-params="{ mouldName: 'settlementNetPriceFile' }"
          :file-data="ruleForm.netPriceFileIds"
          :upload-from-orange-status="true" disabled
          placeholder="请上传网价附件"
        />
      </el-form-item>
      <cy-info-title>补充说明（非必填）</cy-info-title>
      <el-form-item label="补充说明" prop="additionalRemarks" style="width: 100%;">
        <el-input v-model="ruleForm.additionalRemarks" type="textarea" :rows="3" disabled />
      </el-form-item>
      <el-form-item label="补充说明附件" prop="newadditionalFileIds">
        <cy-upload
          ref="fileStorage3"
          :upload-params="{ mouldName: 'settlementSupplementFile' }"
          :file-data="ruleForm.additionalFileIds"
          :upload-from-orange-status="true"
          disabled
          placeholder="请上传补充说明附件"
        />
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import request from '@/utils/request'
import { handleMoney } from '@/utils'

export default {
  name: 'AddSettlement',
  data() {
    this.calculateKeyList = ["purchasePrice", "purchaseTotalPrice", "salesGuaranteeMoney", "salesTotalPrice"]
    return {
      ruleForm: {
        businessName: '',
        customer: {},
        supplier: {},
        platform: {},
        businessNumber: '',
        operatorSupplier: '',
        settlementDate: '',
        settlementAmount: '',
        operatorEnterprise: '',
        settlementStartDate: '',
        settlementEndDate: '',
        countTheGoods: '',
        settleTotalSalesPrice: '',
        repaymentDate: '',
        repaymentAmount: '',
        repayList: [],
        additionalFileIds: [],
        netPriceFileIds: [],
        fileIds: [],
        newfileIds: [],
        newadditionalFileIds: [],
        newnetPriceFileIds: [],
        additionalRemarks: ''
      },
      rules: {
        businessNumber: [{ required: true, trigger: 'change', message: '请选择项目名称' }],
        settlementDate: [{ required: true, trigger: 'change', message: '选择结算日期' }],
        settlementAmount: [{ required: true, trigger: 'blur', message: '请输入结算金额' }],
        operatorSupplier: [{ required: true, trigger: 'blur', message: '请输入经办人（供应商）' }],
        operatorEnterprise: [{ required: true, trigger: 'blur', message: '请选择经办人（核心企业）' }],
        settlementStartDate: [{ required: true, trigger: 'change', message: '请选择开始日期' }],
        settlementEndDate: [{ required: true, trigger: 'change', message: '请选择结束日期' }],
        countTheGoods: [{ required: true, trigger: 'change', message: '请选择结算货物' }],
        settleTotalSalesPrice: [{ required: true, trigger: 'change', message: '请选择结算货物' }],
        repaymentDate: [{ required: true, trigger: 'change', message: '请选择结算日期' }],
        repaymentAmount: [{ required: true, trigger: 'blur', message: '请输入结算金额' }],
        newfileIds: [{ required: true, trigger: 'change', message: '请上传下游结算清单附件' }]
      },
      uploadParams: {},
      businessList: [],
      businessInfo: {},
      coreComList: [],
      supplierComList: [],
      goodsList: [],
      originGoodsList: [],
      buyTotalPrice: 0,
      isLoading: false,
      repayTotalNum: ''
    }
  },
  props: ["info"],
  mounted() {
    // if(this.$route.params.key) {
    //   this.getDetail()
    // } else {
    //   this.getBusinessList()
    // }
  },
  methods: {
    getDetail() {
      request({
        url: '/bill/getDetail',
        method: 'get',
        params: { taskId: this.$route.params.taskId, businessKey: this.$route.params.key }
      }).then(({ data }) => {
        Object.keys(this.ruleForm).forEach(key => {
          if(data.billBasicInformation[key] && !(this.ruleForm[key] instanceof Array)) {
            this.ruleForm[key] = data.billBasicInformation[key]
          }
        })
        if(data.billBasicInformation.operatorEnterprise) {
          this.ruleForm.operatorEnterprise = data.billBasicInformation.operatorEnterprise.split(',').filter(item => !isNaN(item) && Number(item)).map(item => Number(item))
        }
        if(data.billBasicInformation.settlementGoodsInfos) {
          this.goodsList = [ ...data.billBasicInformation.settlementGoodsInfos ]
        }
        this.getBusinessList()
        // this.getBusinessDetail(true)
        this.getCenterComList()
        this.ruleForm.repayList = data.billBasicInformation.settlementRepaymentPlans
        if(this.ruleForm.repayList) {
          // this.calculateRepayNum()
        }
        if(data.billBasicInformation.files) {
          this.ruleForm.fileIds = [ ...data.billBasicInformation.files ]
        }
        if(data.billBasicInformation.netPriceFiles) {
          this.ruleForm.netPriceFileIds = [ ...data.billBasicInformation.netPriceFiles ]
        }
        if(data.billBasicInformation.additionalFiles) {
          this.ruleForm.additionalFileIds = [ ...data.billBasicInformation.additionalFiles ]
        }
      })
    },
    // 获取项目名称列表
    getBusinessList() {
      request({
        url: '/projectInfo/getLocalPurchCompletedProject',
        method: 'get'
      }).then(({ data }) => {
        this.businessList = data || []
      })
    },
    getBusinessDetail(val) {
      request({
        url: '/purchManagement/getPurchCompleted',
        method: 'get',
        params: { businessNumber: this.ruleForm.businessNumber }
      }).then(({ data }) => {
        this.businessInfo = { ...data }
        this.ruleForm.operatorSupplier = data.operatorSupplier
        if(val) {
          this.calculateNum()
        }
      })
    },
    // 获取经办人（核心企业）列表
    getCenterComList() {
      request({
        url: '/bill/findOperatorByBusinessNumber',
        method: 'get',
        params: { businessNumber: this.ruleForm.businessNumber }
      }).then(({ data }) => {
        this.coreComList = data || []
      })
    },
    calculateNum() {
      if(!this.goodsList || this.goodsList.length === 0) {
        this.$message.error('请选择货物')
        return
      }
      let data = {
        supplierId: this.businessInfo.supplierId,
        businessNumber: this.ruleForm.businessNumber,
        acceptanceGoodsInfos: this.goodsList
      }
      request({
        url: '/bill/calculation',
        method: 'post',
        data
      }).then(({ data }) => {
        this.goodsList.forEach((item, index) => {
          this.calculateKeyList.forEach(key => {
            item[key] = data[index][key]
          })
        })
        this.calculateTotal()
      })
    },
    calculateTotal() {
      let num = 0, price = 0, buyPrice = 0;
      this.goodsList.forEach(item => {
        num = parseFloat(Number(num) + Number(item.goodsQuantity || 0)).toFixed(4)
        price = parseFloat(Number(price) + Number(item.salesTotalPrice || 0)).toFixed(2)
        buyPrice = parseFloat(Number(buyPrice) + Number(item.purchaseTotalPrice || 0)).toFixed(2)
      })
      this.ruleForm.countTheGoods = num
      this.ruleForm.settleTotalSalesPrice = price
      this.buyTotalPrice = buyPrice
    },
    confirmRepay() {
      let arr = []
      this.$refs.ruleForm.validateField(["repaymentDate", "repaymentAmount"], flag => {
        if(!flag) {
          arr.push(1)
        } else {
          arr = []
        }
      })
      if(arr.length == 2) {
        this.ruleForm.repayList.push({
          repaymentDate: this.ruleForm.repaymentDate,
          repaymentAmount: this.ruleForm.repaymentAmount
        })
        this.calculateRepayNum()
        this.$refs.dialog.show = false
      }
    },
    calculateRepayNum() {
      this.repayTotalNum = this.ruleForm.repayList.reduce((t, i) => {
        t = parseFloat(Number(t) + Number(i.repaymentAmount)).toFixed(2)
        console.log(t, 'helo', i.repaymentAmount)
        return t
      }, 0)
      this.repayTotalNum = handleMoney(this.repayTotalNum)
    }
  },
  computed: {
    changeNum1() {
      return handleMoney(this.ruleForm.countTheGoods)
    },
    changeNum2() {
      return handleMoney(this.ruleForm.settleTotalSalesPrice)
    },
    changeNum3() {
      return handleMoney(this.buyTotalPrice)
    }
  },
  watch: {
    'info.mathId': {
      handler(newV) {
        if(newV) {
          Object.keys(this.ruleForm).forEach(key => {
            if(this.info[key] && !(this.ruleForm[key] instanceof Array)) {
              this.ruleForm[key] = this.info[key]
            }
          })
          if(this.info.settlementGoodsInfos) {
            this.goodsList = [ ...this.info.settlementGoodsInfos ]
            this.calculateTotal()
          }
          this.ruleForm.repayList = this.info.settlementRepaymentPlans
          if(this.ruleForm.repayList) {
            this.calculateRepayNum()
          }
          if(this.info.files) {
            this.ruleForm.fileIds = [ ...this.info.files ]
          }
          if(this.info.netPriceFiles) {
            this.ruleForm.netPriceFileIds = [ ...this.info.netPriceFiles ]
          }
          if(this.info.additionalFiles) {
            this.ruleForm.additionalFileIds = [ ...this.info.additionalFiles ]
          }
        }
      },
      immediate: true
    }
  }
}
</script>

<style lang="scss">
.line-form-item {
  display: flex;
  flex-direction: row;
  width: 100% !important;
  .el-form-item__label {
    margin-right: 10px;
  }
  .el-form-item__content {
    flex-grow: 1;
    .el-input {
      height: 42px;
      line-height: 42px;
    }
  }
}
</style>
