<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-input v-model="businessInfo.businessNumber" disabled />
      </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="operatorSupplier">
        <el-input v-model="ruleForm.operatorSupplier" placeholder="请输入经办人（供应商）" /> 
      </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> -->
        <template slot="right">
          <span style="color: #FE7D0B; margin-right: 20px; cursor: pointer;" @click="calculateNum">一键计算质保金</span>
          <!-- <span style="color: #FE7D0B; margin-right: 20px; cursor: pointer;" @click="downFile">下载模板</span>
          <label for="uploadInput" style="color: #FE7D0B; font-weight: normal; cursor: pointer;">模板导入</label>
          <input type="file" id="uploadInput" style="display: none;" accept="xls, .xlsx, .excel" @change="importFile" /> -->
        </template>
      </cy-info-title>
      <div style="width: 100%; margin-bottom: 20px;">
        <el-table :data="ruleForm.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">
              {{ 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"
                />
              </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"
                /> -->
              </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"
                /> -->
              </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>
        <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="补充说明" style="width: 100%;">
        <el-input v-model="ruleForm.additionalRemarks" />
      </el-form-item>
      <el-form-item label="补充说明文件">
        <cy-upload
          ref="fileStorage"
          :upload-params="{ fileType: 'settlementSupplementFile' }"
          :file-data="ruleForm.additionalFileIds"
          :upload-from-orange-status="true"
          placeholder="请上传附件"
        />
      </el-form-item>
    </el-form>
    <div class="submit-btn">
      <el-button @click="$router.go(-1)">关闭</el-button>
      <el-button type="primary" @click="confirm">提交</el-button>
    </div>
  </div>
</template>

<script>
import request from '@/utils/request'
import { handleMoney, fourMoney } from '@/utils'
import { exportFile } from '@/utils/index'

export default {
  name: 'AddSettlement',
  data() {
    this.calculateKeyList = ["purchasePrice", "purchaseTotalPrice", "salesGuaranteeMoney", "salesTotalPrice", "purchaseGuaranteeMoney", "salesPrice"]
    return {
      ruleForm: {
        operatorSupplier: '',
        additionalFileIds: [],
        countTheGoods: '',
        settleTotalSalesPrice: '',
        businessNumber: '',
        additionalRemarks: '',
        goodsList: [],
        settlementAmount: ''
      },
      buyTotalPrice: '',
      rules: {
        operatorSupplier: [{ required: true, trigger: 'blur', message: '请输入经办人（供应商）' }]
      },
      businessInfo: {},
      goodsList: [],
      isLoading: false
    }
  },
  mounted() {
    this.getDetail()
  },
  methods: {
    openSaleDialog() {

    },
    getDetail() {
      request({
        url: '/bill/getDetail',
        method: 'get',
        params: { taskId: this.$route.query.taskId, businessKey: this.$route.query.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.settlementGoodsInfos) {
          this.ruleForm.goodsList = [ ...data.billBasicInformation.settlementGoodsInfos ]
          this.calculateTotal()
        }
        if(data.billBasicInformation.additionalFiles) {
          this.ruleForm.additionalFileIds = [ ...data.billBasicInformation.additionalFiles ]
        }
        this.getBusinessDetail()
      })
    },
    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
    },
    getBusinessDetail() {
      request({
        url: '/purchManagement/getPurchCompleted',
        method: 'get',
        params: { businessNumber: this.ruleForm.businessNumber }
      }).then(({ data }) => {
        this.businessInfo = { ...data }
        // this.ruleForm.operatorSupplier = data.operatorSupplier
      })
    },
    confirm() {
      this.$refs.ruleForm.validate(flag => {
        if(flag) {
          if(this.ruleForm.goodsList.length === 0) {
            this.$message.error('请导入货物')
          } else {
            this.calculateNum('submit')
            // this.submit()
          }
        }
      })
    },
    submit() {
      // this.isLoading = true
      let data = {
        Loading: true,
        businessKey: this.$route.query.key,
        id: this.$route.query.key,
        settlementGoodsInfos: this.ruleForm.goodsList.map(item => {
          item.acceptanceGoodsInfoId = item.id
          return item
        }),
        ...this.ruleForm
      }
      let arr = [...this.$refs.fileStorage.fileLists]
      data.additionalFileIds = arr.map(item => {
        if(item.response) {
          return item.response.data.id
        } else {
          return item.id
        }
      })
      request({
        url: '/bill/billUnitPriceAdjust',
        method: 'post',
        data
      }).then(() => {
        // this.isLoading = false
        this.$message.success('提交成功')
        this.$router.go(-1)
      }, () => {
        // this.isLoading = false
      })
    },
    downFile() {
      request({
        url: '/bill/downloadFile',
        method: 'post',
        responseType: 'arraybuffer'
      }).then(data => {
        exportFile(data)
      })
    },
    importFile(e) {
      const file = e.target.files[0] || e.dataTransfer.files[0]// 用于提交
      const data = new FormData()
      data.append('file', file)
      request({
        url: '/bill/doImportGoodsInfo',
        method: 'post',
        data
      }).then(({ data }) => {
        this.ruleForm.goodsList = [ ...data ]
        this.calculateTotal()
      })
      e.target.value = ''
    },
    calculateNum(type) {
      if(!this.ruleForm.goodsList || this.ruleForm.goodsList.length === 0) {
        this.$message.error('请选择货物')
        return
      }
      let data = {
        supplierId: this.businessInfo.supplierId,
        businessNumber: this.businessInfo.businessNumber,
        acceptanceGoodsInfos: this.ruleForm.goodsList,
        Loading: true
      }
      // this.isLoading = true
      request({
        url: '/bill/calculation',
        method: 'post',
        data
      }).then(({ data }) => {
        this.ruleForm.goodsList.forEach((item, index) => {
          this.calculateKeyList.forEach(key => {
            item[key] = data[index][key]
          })
          item.purchaseGuaranteeMoney = data[index].purchaseGuaranteeMoney
        })
        this.calculateTotal()
        // this.isLoading = false
        if(type == 'submit') {
          this.submit()
        }
      }, () => {
        // this.isLoading = false
      })
    },
  },
  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>