<template>
  <div>
    <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">
        <el-select v-model="ruleForm.businessNumber" style="width: 100%" placeholder="请选择项目名称" @change="selectProject">
          <el-option v-for="(item, index) in businessList" :key="index + '_business'"
            :label="item.projectName" :value="item.businessNumber" />
        </el-select>
      </el-form-item>
      <el-form-item label="核心企业名称">
        <el-input v-model="businessInfo.coreEnterpriseName" disabled />
      </el-form-item>
      <el-form-item label="供应商（主体）名称">
        <el-input v-model="businessInfo.mainEnterpriseName" disabled />
      </el-form-item>
      <el-form-item label="贸易平台">
        <el-input v-model="businessInfo.platformName" disabled />
      </el-form-item>
      <el-form-item label="业务编号">
        <el-input v-model="businessInfo.businessNumber" disabled />
      </el-form-item>
      <el-form-item label="结算日期" prop="settlementDate">
        <el-date-picker v-model="ruleForm.settlementDate" value-format="yyyy-MM-dd" type="date" placeholder="选择结算日期" style="width: 100%;" />
      </el-form-item>
      <el-form-item label="结算金额" prop="settlementAmount">
        <el-input v-model="ruleForm.settlementAmount" placeholder="请输入结算金额" />
      </el-form-item>
      <el-form-item label="经办人（供应商）" prop="operatorSupplier">
        <el-input v-model="ruleForm.operatorSupplier" placeholder="请输入经办人（供应商）" /> 
      </el-form-item>
      <el-form-item label="经办人（核心企业）" prop="operatorEnterprise">
        <el-input v-model="ruleForm.operatorEnterprise" placeholder="请输入经办人（核心企业）" @blur="changeCoreCom" /> 
        <!-- <el-select v-model="ruleForm.operatorEnterprise" style="width: 100%" placeholder="请选择经办人（核心企业）" multiple>
          <el-option v-for="(item, index) in coreComList" :key="index + '_business'"
            :label="item.name" :value="item.name" />
        </el-select> -->
      </el-form-item>
      <cy-info-title style="margin-top: 15px;">货物信息（下游结算）
        <span style="font-size: 12px; color: #A3A8AC;">单位：元</span>
        <template slot="right">
          <span style="color: #FE7D0B; margin-right: 20px;" @click="calculateNum">一键计算质保金</span>
          <span style="color: #FE7D0B;" @click="openSaleDialog">选择已验收货物</span>
        </template>
      </cy-info-title>
      <div style="width: 100%; margin-bottom: 20px;">
        <el-table :data="ruleForm.goodsList" style="width: 100%;" 
          :span-method="combineRow">
          <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">
              {{ scope.row.acceptanceDate ? scope.row.acceptanceDate.split(' ')[0] : '' }}
            </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="数量" width="150">
            <template slot-scope="scope">
              <el-form-item label="" :prop="`goodsList[${scope.$index}].goodsQuantity`" style="width: 100%;"
                :rules="[{ required: true, message: '请输入数量', trigger: 'blur' }]">
                <el-input
                  v-model="scope.row.goodsQuantity"
                  placeholder="请输入数量"
                  @change="calculateNum"
                  style="width: 100%;"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="referencePrice" label="参考价格" width="150">
            <template slot="header" slot-scope="scope">
              <el-tooltip class="item" effect="dark" content="网价" placement="top">
                <span class="table-tip-icon">!</span>
              </el-tooltip>
              <span>参考价格</span>
            </template>
            <template slot-scope="scope">
              <el-form-item label="" :prop="`goodsList[${scope.$index}].referencePrice`" style="width: 100%;"
                :rules="[{ required: true, message: '请输入参考价格', trigger: 'blur' }]">
                <cy-amount-input
                  v-model="scope.row.referencePrice"
                  placeholder="请输入参考价格"
                  @change="calculateNum"
                  style="width: 100%;"
                />
                <!-- <el-input
                  v-model="scope.row.referencePrice"
                  placeholder="请输入参考价格"
                  @change="calculateTotal"
                  style="width: 100%;"
                /> -->
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="floatingPrice" label="浮动价格" width="150">
            <template slot="header" slot-scope="scope">
              <el-tooltip class="item" effect="dark" content="合约中约定的上下浮动差价" placement="top">
                <span class="table-tip-icon">!</span>
              </el-tooltip>
              <span>浮动价格</span>
            </template>
            <template slot-scope="scope">
              <el-form-item label="" :prop="`goodsList[${scope.$index}].floatingPrice`" style="width: 100%;"
                :rules="[{ required: true, message: '请输入浮动价格', trigger: 'blur' }]">
                <cy-amount-input
                  v-model="scope.row.floatingPrice"
                  placeholder="请输入浮动价格"
                  @change="calculateNum"
                  style="width: 100%;"
                />
                <!-- <el-input
                  v-model="scope.row.floatingPrice"
                  placeholder="请输入浮动价格"
                  @change="calculateTotal"
                  style="width: 100%;"
                /> -->
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="salesPrice" label="销售单价">
            <!-- <template slot-scope="scope">
              <el-form-item label="" :prop="`goodsList[${scope.$index}].salesPrice`" style="width: 100%;"
                :rules="[{ required: true, message: '请输入销售单价', trigger: 'blur' }]">
                <cy-amount-input
                  v-model="scope.row.salesPrice"
                  placeholder="请输入销售单价"
                  @change="calculateNum"
                  style="width: 100%;"
                />
              </el-form-item>
            </template> -->
          </el-table-column>
          <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-column prop="purchGuaranteeMoney" label="操作">
            <template slot-scope="scope">
              <el-tooltip class='item' effect='dark' content="删除" placement='top' >
                <span style="cursor: pointer; color: #6bcafc;" @click="deleteGoods(scope.row.acceptanceGoodsNumber)">删除</span>
              </el-tooltip>
            </template>
          </el-table-column>
        </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">
        <el-date-picker v-model="ruleForm.settlementStartDate" value-format="yyyy-MM-dd" type="date" placeholder="选择开始日期" style="width: 100%;" @change="calculateEndDate" />
      </el-form-item>
      <el-form-item label="结束日期" prop="settlementEndDate">
        <el-date-picker v-model="ruleForm.settlementEndDate" value-format="yyyy-MM-dd" type="date" placeholder="选择结束日期" style="width: 100%;" />
      </el-form-item>
      <cy-info-title style="margin-top: 15px;">回款计划
        <!-- <span style="font-size: 12px; color: #A3A8AC;">单位：元</span> -->
        <template slot="right">
          <span style="color: #FE7D0B;" @click="addRepayment">添加</span>
        </template>
      </cy-info-title>
      <div style="width: 100%; margin-bottom: 20px;">
        <el-table :data="ruleForm.repayList" style="width: 100%;">
          <el-table-column type="index" label="编号" width="300" 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-column prop="purchGuaranteeMoney" label="操作">
            <template slot-scope="scope">
              <el-tooltip class='item' effect='dark' content="删除" placement='top' >
                <span style="cursor: pointer; color: #6bcafc;" @click="ruleForm.repayList.splice(scope.$index, 1), calculateRepayNum()">删除</span>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <div style="margin-top: 10px;">
          <b v-show="repayTotalNum" style="margin: 0 20px; color: #FF0000;">合计：{{ repayTotalNum }}</b>
        </div>
      </div>
      <cy-info-title>结算文件（下游）</cy-info-title>
      <el-form-item label="下游结算清单附件" prop="newfileIds">
        <cy-upload
          ref="fileStorage1"
          :upload-params="{ fileType: 'settlementFile' }"
          :file-data="ruleForm.fileIds"
          :upload-from-orange-status="true"
          placeholder="请上传网价附件"
        />
      </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="margin-right: 0;">
        <cy-upload
          ref="fileStorage2"
          :upload-params="{ fileType: 'settlementNetPriceFile' }"
          :file-data="ruleForm.netPriceFileIds"
          :upload-from-orange-status="true"
          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" placeholder="请输入补充说明" />
      </el-form-item>
      <el-form-item label="补充说明附件" prop="newadditionalFileIds">
        <cy-upload
          ref="fileStorage3"
          :upload-params="{ fileType: 'settlementSupplementFile' }"
          :file-data="ruleForm.additionalFileIds"
          :upload-from-orange-status="true"
          placeholder="请上传补充说明附件"
        />
      </el-form-item>
      <cy-dialog ref="dialog" title="回款计划添加">
        <el-form-item label="回款日期：" prop="repaymentDate" class="line-form-item" style="margin-bottom: 20px;">
          <el-date-picker v-model="ruleForm.repaymentDate" value-format="yyyy-MM-dd" type="date"  placeholder="请选择回款日期" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="回款金额：" prop="repaymentAmount" class="line-form-item">
          <el-input v-model="ruleForm.repaymentAmount" placeholder="请输入回款金额" />
        </el-form-item>
        <template slot="footer">
          <el-button @click="$refs.dialog.show = false">关闭</el-button>
          <el-button type="primary" @click="confirmRepay">确定</el-button>
        </template>
      </cy-dialog>
      <cy-dialog ref="chooseGood" title="选择货物">
        <choose-goods-vue ref="goodsTable" :originList="originGoodsList" :info="businessInfo"></choose-goods-vue>
        <template slot="footer">
          <el-button @click="$refs.chooseGood.show = false">关闭</el-button>
          <el-button type="primary" @click="confirmGoods">确定</el-button>
        </template>
      </cy-dialog>
    </el-form>
    <div class="submit-btn">
      <el-button @click="confirmPage(true)" style="position: absolute; left: 20px;" :loading="loading">预览上游结算单</el-button>
      <el-button @click="$router.go(-1)">关闭</el-button>
      <el-button type="primary" @click="submit(1)">暂存</el-button>
      <el-button type="primary" @click="confirmPage">提交</el-button>
    </div>
  </div>
</template>

<script>
import request from '@/utils/request'
import chooseGoodsVue from './components/chooseGoods.vue'
import { handleMoney, fourMoney } from '@/utils'

export default {
  name: 'AddSettlement',
  data() {
    this.calculateKeyList = ["purchasePrice", "purchaseTotalPrice", "salesGuaranteeMoney", "salesTotalPrice", "purchaseGuaranteeMoney", "salesPrice"]
    return {
      ruleForm: {
        businessNumber: '',
        operatorSupplier: '',
        settlementDate: '',
        settlementAmount: '',
        operatorEnterprise: '',
        settlementStartDate: '',
        settlementEndDate: '',
        countTheGoods: '',
        settleTotalSalesPrice: '',
        repaymentDate: '',
        repaymentAmount: '',
        repayList: [],
        additionalFileIds: [],
        netPriceFileIds: [],
        fileIds: [],
        newfileIds: [],
        newadditionalFileIds: [],
        newnetPriceFileIds: [],
        goodsList: [],
        additionalRemarks: ''
      },
      rules: {
        businessNumber: [{ required: true, trigger: 'change', message: '请选择项目名称' }],
        settlementDate: [{ required: true, trigger: 'change', message: '选择结算日期' }],
        settlementAmount: [{ required: true, trigger: 'blur', message: '请输入结算金额' }],
        operatorSupplier: [{ required: true,  message: '请输入经办人（供应商）', trigger: 'blur' }],
        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: '请上传下游结算清单附件' }],
        additionalRemarks: [{ required: false, trigger: 'blur', message: '请输入补充说明' }]
      },
      uploadParams: {},
      businessList: [],
      businessInfo: {},
      coreComList: [],
      supplierComList: [],
      goodsList: [],
      originGoodsList: [],
      buyTotalPrice: 0,
      isLoading: false,
      repayTotalNum: '',
      originOperatorEnterprise: '',
      loading: false
    }
  },
  components: { chooseGoodsVue },
  mounted() {
    if(this.$route.query.key) {
      this.getDetail()
    } else {
      // this.getCenterComList()
      this.getBusinessList()
    }
  },
  methods: {
    getDetail() {
      request({
        url: '/bill/getDetail',
        method: 'get',
        params: { taskId: this.$route.query.taskId, businessKey: this.$route.query.key,
          Loading: true }
      }).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(',')
        // }
        if(data.billBasicInformation.settlementGoodsInfos) {
          // arr.forEach(item => {
          //   item.acceptanceGoodInfos[0].colspanLength = item.acceptanceGoodInfos.length
          //   this.ruleForm.goodsList = this.ruleForm.goodsList.concat(item.acceptanceGoodInfos)
          // })
          // this.ruleForm.goodsList = [ ...data.billBasicInformation.settlementGoodsInfos ]
          this.ruleForm.goodsList = data.billBasicInformation.settlementGoodsInfos.reduce((total, item) => {
            if(total.some(i => i.acceptanceGoodsNumber == item.acceptanceGoodsNumber)) {
              total.push(item)
              return total
            } else {
              item.colspanLength = data.billBasicInformation.settlementGoodsInfos.filter(goods => goods.acceptanceGoodsNumber == item.acceptanceGoodsNumber).length
              total.push(item)
              return total
            }
          }, [])
          this.originGoodsList = this.ruleForm.goodsList.reduce((total, item) => {
            if(total.some(i => i.id == item.acceptanceGoodsNumber)) {
              return total
            } else {
              total.push({id: item.acceptanceGoodsNumber})
              return total
            }
          }, [])
          this.calculateTotal()
        }
        this.getBusinessList()
        this.getBusinessDetail()
        // 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 ]
        }
        this.originOperatorEnterprise = this.ruleForm.operatorEnterprise || ''
      })
    },
    // 获取项目名称列表
    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 = { source: 'jiesuan', ...data }
        if(val) {
          this.ruleForm.operatorSupplier = data.operatorSupplier
        }
        // this.ruleForm.operatorSupplier = data.operatorSupplier
        // if(val && this.ruleForm.goodsList.length) {
        //   this.calculateNum()
        // }
      })
    },
    // 获取经办人（核心企业）列表
    getCenterComList() {
      request({
        url: '/bill/findOperatorByBusinessNumber',
        method: 'get',
        params: { businessNumber: this.ruleForm.businessNumber }
      }).then(({ data }) => {
        this.coreComList = data || []
        this.ruleForm.operatorEnterprise = this.originOperatorEnterprise = data.map(item => item.name).join(',')
        this.rules.additionalRemarks[0].required = false
      })
    },
    changeCoreCom() {
      this.rules.additionalRemarks[0].required = this.ruleForm.operatorEnterprise != this.originOperatorEnterprise
    },
    openSaleDialog() {
      if(this.ruleForm.businessNumber) {
        this.$refs.chooseGood.show = true
      } else {
        this.$message.error('请选择项目')
      }
    },
    addRepayment() {
      this.ruleForm.repaymentDate = ''
      this.ruleForm.repaymentAmount = ''
      this.$refs.dialog.show = true
    },
    selectProject() {
      if(this.ruleForm.businessNumber) {
        this.getBusinessDetail(true)
        this.getCenterComList()
        this.ruleForm.settlementDate = ''
        this.ruleForm.settlementAmount = ''
        this.ruleForm.operatorEnterprise = ''
        this.ruleForm.goodsList = []
        this.originGoodsList = []
      }
    },
    submitForm() {},
    confirmGoods() {
      let arr = this.$refs.goodsTable.selectedInfos
      if(!arr || arr.length === 0) {
        this.$message.error('请选择货物')
        return
      }
      this.originGoodsList = [ ...arr ]
      this.ruleForm.goodsList = []
      arr.forEach(item => {
        item.acceptanceGoodInfos[0].colspanLength = item.acceptanceGoodInfos.length
        this.ruleForm.goodsList = this.ruleForm.goodsList.concat(item.acceptanceGoodInfos)
      })
      this.calculateTotal()
      this.$refs.chooseGood.show = false
    },
    deleteGoods(id) {
      this.$confirm('确定删除该批次下的所有货物？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.ruleForm.goodsList = this.ruleForm.goodsList.reduce((total, item) => {
          if(item.acceptanceGoodsNumber != id) {
            total.push(item)
          }
          return total
        }, [])
        this.originGoodsList = this.originGoodsList.reduce((total, item) => {
          if(item.id != id) {
            total.push(item)
          }
          return total
        }, [])
        this.calculateTotal()
      })
    },
    calculateNum(type) {
      if(!this.ruleForm.goodsList || this.ruleForm.goodsList.length === 0) {
        this.$message.error('请选择货物')
        return
      }
      // this.isLoading = true
      let data = {
        supplierId: this.businessInfo.supplierId,
        businessNumber: this.ruleForm.businessNumber,
        acceptanceGoodsInfos: this.ruleForm.goodsList,
        Loading: true
      }
      request({
        url: '/bill/calculation',
        method: 'post',
        data
      }).then(({ data }) => {
        
        // } else {
          this.ruleForm.goodsList.forEach((item, index) => {
            this.calculateKeyList.forEach(key => {
              item[key] = data[index][key]
            })
            // item.purchaseGuaranteeMoney = data[index].purchaseGuaranteeMoney
          })
          this.calculateTotal()
          if(type == 'submit') {
            this.submit(2)
          }
          // this.isLoading = false
        // }
      }, () => {
        // this.isLoading = false
      })
    },
    calculateTotal() {
      let num = 0, price = 0, buyPrice = 0;
      this.ruleForm.goodsList.forEach(item => {
        num = parseFloat(Number(num) + Number(item.goodsQuantity || 0)).toFixed(4)
        price = parseFloat(Number(price) + (Number(item.goodsQuantity || 0) * Number(item.salesPrice || 0))).toFixed(4)
        buyPrice = parseFloat(Number(buyPrice) + Number(item.purchaseTotalPrice || 0)).toFixed(2)
      })
      this.ruleForm.countTheGoods = num
      this.ruleForm.settleTotalSalesPrice = parseFloat(price).toFixed(2)
      this.ruleForm.settlementAmount = parseFloat(price).toFixed(2)
      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
      }
    },
    confirmPage(val) {
      this.ruleForm.newfileIds = [...this.ruleForm.fileIds, ...this.$refs.fileStorage1.fileLists]
      this.$refs.ruleForm.validate(flag => {
        if(flag) {
          if(val === true) {
            this.createPdf()
          } else {
            this.calculateNum('submit')
            // this.submit(2)
          }
        }
      })
    },
    submit(flag) {
      if(!this.ruleForm.businessNumber) {
        this.$message.error('请锁定业务编号后暂存')
        return
      }
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      // this.isLoading = true
      let data = new FormData()
      if(this.$route.query.key) {
        data.append('businessKey', this.$route.query.key)
        data.append('id', this.$route.query.key)
      }
      if(this.$route.query.taskId) {
        data.append('taskId', this.$route.query.taskId)
      }
      data.append('supplierId', this.businessInfo.supplierId)
      data.append('businessNumber', this.ruleForm.businessNumber)
      data.append('businessName', this.businessInfo.projectName)
      data.append('enterpriseCustomerInfoId', this.businessInfo.coreEnterpriseId)
      data.append('tradingPlatformId', this.businessInfo.platformId)
      data.append('settlementDate', this.ruleForm.settlementDate);
      data.append('settlementAmount', this.ruleForm.settlementAmount);
      data.append('operatorSupplier', this.ruleForm.operatorSupplier);
      data.append('additionalRemarks', this.ruleForm.additionalRemarks)
      // if(this.ruleForm.operatorEnterprise.length) {
      data.append('operatorEnterprise', this.ruleForm.operatorEnterprise)
      data.append('Loading', true)
      // }
      if(this.ruleForm.goodsList.length) {
        this.ruleForm.goodsList.forEach((item, index) => {
          Object.keys(item).forEach(key => {
            if((item[key] || item[key] === 0) && key !== 'id' && key !== 'gmtCreate' && key !== 'gmtModified') {
              data.append(`settlementGoodsInfos[${index}].${key}`, item[key])
            }
          })
          data.append(`settlementGoodsInfos[${index}].acceptanceGoodsInfoId`, item.id)
        })
      }
      data.append('settlementStartDate', this.ruleForm.settlementStartDate)
      data.append('settlementEndDate', this.ruleForm.settlementEndDate)
      if(this.ruleForm.repayList.length) {
        this.ruleForm.repayList.forEach((item, index) => {
          data.append(`settlementRepaymentPlans[${index}].repaymentDate`, item.repaymentDate)
          data.append(`settlementRepaymentPlans[${index}].repaymentAmount`, item.repaymentAmount)
        })
      }
      let arr1 = [...this.ruleForm.fileIds, ...this.$refs.fileStorage1.fileLists];
      let arr2 = [...this.ruleForm.netPriceFileIds, ...this.$refs.fileStorage2.fileLists];
      let arr3 = [...this.ruleForm.additionalFileIds, ...this.$refs.fileStorage3.fileLists];
      arr1.forEach((item, index) => {
        data.append(`fileIds[${index}]`, item.response?.data?.id || item.id)
      });
      arr2.forEach((item, index) => {
        data.append(`netPriceFileIds[${index}]`, item.response?.data?.id || item.id)
      });
      arr3.forEach((item, index) => {
        data.append(`additionalFileIds[${index}]`, item.response?.data?.id || item.id)
      });
      data.append('submit', flag == 2)
      request({
        url: this.$route.query.key ? '/bill/updateBill' : '/bill/addBillBasicInformation',
        method: 'post',
        data
      }).then(() => {
        // this.isLoading = false
        this.$message.success('提交成功')
        this.$router.go(-1)
        loading.close()
      }, () => {
        loading.close()
        // this.isLoading = false
      })
    },
    calculateEndDate() {
      if(!this.ruleForm.businessNumber) {
        this.$message.error('请选择项目')
        return
      }
      request({
        url: '/bill/getExpectedSettlementDate',
        method: 'post',
        data: { businessNumber: this.ruleForm.businessNumber, settlementStartDate: this.ruleForm.settlementStartDate, supplierId: this.businessInfo.supplierId }
      }).then(({ data }) => {
        this.ruleForm.settlementEndDate = data.settlementEndDate
      })
    },
    createPdf() {
      if(!this.ruleForm.businessNumber) {
        this.$message.error('请锁定业务编号后暂存')
        return
      }
      this.loading = true
      let data = new FormData()
      if(this.$route.query.key) {
        data.append('businessKey', this.$route.query.key)
        data.append('id', this.$route.query.key)
      }
      if(this.$route.query.taskId) {
        data.append('taskId', this.$route.query.taskId)
      }
      data.append('supplierId', this.businessInfo.supplierId)
      data.append('businessNumber', this.ruleForm.businessNumber)
      data.append('businessName', this.businessInfo.projectName)
      data.append('enterpriseCustomerInfoId', this.businessInfo.coreEnterpriseId)
      data.append('tradingPlatformId', this.businessInfo.platformId)
      data.append('settlementDate', this.ruleForm.settlementDate);
      data.append('settlementAmount', this.ruleForm.settlementAmount);
      data.append('operatorSupplier', this.ruleForm.operatorSupplier);
      data.append('additionalRemarks', this.ruleForm.additionalRemarks)
      // if(this.ruleForm.operatorEnterprise.length) {
      data.append('operatorEnterprise', this.ruleForm.operatorEnterprise)
      // }
      if(this.ruleForm.goodsList.length) {
        this.ruleForm.goodsList.forEach((item, index) => {
          Object.keys(item).forEach(key => {
            if((item[key] || item[key] === 0) && key !== 'id' && key !== 'gmtCreate' && key !== 'gmtModified') {
              data.append(`settlementGoodsInfos[${index}].${key}`, item[key])
            }
          })
          data.append(`settlementGoodsInfos[${index}].acceptanceGoodsInfoId`, item.id)
        })
      }
      data.append('settlementStartDate', this.ruleForm.settlementStartDate)
      data.append('settlementEndDate', this.ruleForm.settlementEndDate)
      if(this.ruleForm.repayList.length) {
        this.ruleForm.repayList.forEach((item, index) => {
          data.append(`settlementRepaymentPlans[${index}].repaymentDate`, item.repaymentDate)
          data.append(`settlementRepaymentPlans[${index}].repaymentAmount`, item.repaymentAmount)
        })
      }
      if(this.$refs.fileStorage1.fileLists.length > 0) {
        this.$refs.fileStorage1.fileLists.forEach((item, index) => {
          data.append(`fileIds[${index}]`, item.response?.data?.id || item.id)
        });
      }
      if(this.$refs.fileStorage2.fileLists.length > 0) {
        this.$refs.fileStorage2.fileLists.forEach((item, index) => {
          data.append(`netPriceFileIds[${index}]`, item.response?.data?.id || item.id)
        });
      }
      if(this.$refs.fileStorage3.fileLists.length > 0) {
        this.$refs.fileStorage3.fileLists.forEach((item, index) => {
          data.append(`additionalFileIds[${index}]`, item.response?.data?.id || item.id)
        });
      }
      request({
        url: '/bill/downloadPdf',
        method: 'post',
        data
      }).then(({ data }) => {
        this.loading = false
        let myBlob = this.dataURLtoBlob(data)
        let myUrl = URL.createObjectURL(myBlob)
        window.open(myUrl, '_blank')
      }, () => {
        this.loading = false
      })
    },
    dataURLtoBlob(data) {
      let arr = data.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], { type: mime });
    },
    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)
    },
    combineRow({ row, columnIndex }) {
      const merge = row.colspanLength ? row.colspanLength : 0
      // const _colMerge = merge > 0 ? 1 : 0
      if (columnIndex === 16) {
        return {
          rowspan: merge,
          colspan: 1
        }
      }
    }
  },
  computed: {
    changeNum1() {
      return fourMoney(this.ruleForm.countTheGoods)
    },
    changeNum2() {
      return handleMoney(this.ruleForm.settleTotalSalesPrice)
    },
    changeNum3() {
      return handleMoney(this.buyTotalPrice)
    }
  }
}
</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;
    }
  }
}
.table-tip-icon {
  display: inline-block;
  width: 14px;
  height: 14px;
  border-radius: 7px;
  line-height: 14px;
  text-align: center;
  border: 1px solid #ff0000;
  color: #ff0000;
  margin-right: 5px;
}
</style>