<template>
  <div class="apply-invoicing-content">
    <cy-info-title>基础信息</cy-info-title>
    <basic-information ref="basicInformation" :basic-information="basicInformation" :basic-disabled="basicDisabled" @invoiceInformation="getInvoiceInformation" />
    <cy-info-title>开票信息</cy-info-title>
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-position="top"
      label-width="150px"
      class="rule-form-orange"
    >
      <el-form-item label="公司名称" prop="enterpriseName">
        <el-input
          v-model="ruleForm.enterpriseName"
          placeholder="请输入公司名称"
          class="two-form-item"
          disabled
        />
      </el-form-item>
      <el-form-item label="纳税识别号" prop="socialCreditCode">
        <el-input
          v-model="ruleForm.socialCreditCode"
          placeholder="请输入纳税识别号"
          :disabled="disabled"
        />
      </el-form-item>
      <el-form-item label="电话" prop="phoneNumber">
        <el-input
          v-model="ruleForm.phoneNumber"
          placeholder="请输入手机号"
          :disabled="disabled"
        />
      </el-form-item>
      <el-form-item label="地址" class="two-form-item" prop="address">
        <el-input
          v-model="ruleForm.address"
          placeholder="请输入地址"
          :disabled="disabled"
        />
      </el-form-item>
      <el-form-item label="开户行名称" prop="accountBankName">
        <el-input
          v-model="ruleForm.accountBankName"
          placeholder="请输入开户行名称"
          :disabled="disabled"
        />
      </el-form-item>
      <el-form-item label="开户账号" prop="accountNumber">
        <el-input
          v-model="ruleForm.accountNumber"
          placeholder="请输入开户账号"
          :disabled="disabled"
        />
      </el-form-item>
      <el-form-item label="发票类型" prop="invoiceType">
        <el-radio-group v-model="ruleForm.invoiceType" :disabled="disabled">
          <el-radio
            v-for="item in constant.invoiceType"
            :key="item.code"
            :label="item.code"
          >
            {{ item.name }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="金额种类" prop="amountKind">
        <el-select v-model="ruleForm.amountKind" placeholder="请选择金额种类" disabled>
          <el-option
            v-for="item in constant.amountKind"
            :key="item.code"
            :label="item.name"
            :value="item.code"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="开票金额" prop="openAmount">
        <cy-amount-input
          v-model="ruleForm.openAmount"
          placeholder="请输入开票金额"
          disabled
        />
      </el-form-item>
      <el-form-item label="备注信息" prop="remark">
        <el-input
          v-model="ruleForm.remark"
          placeholder="请输入备注信息"
          :disabled="disabled"
        />
      </el-form-item>
      <cy-info-title style="margin-bottom:20px">
        <span>
          货物信息
          <span class="statistics">总金额合计： <span>{{ formatMoney(openAmountTotal) }}</span></span>
          <span class="statistics">本次开票数量合计： <span>{{ fourMoney(openQuantityTotal) }}</span></span>
        </span>
        <template v-if="!disabled" slot="right">
          <div style="float:right" class="iconfont icon-Union-11 iconCharacters" @click="select('selectGoods')">选择已结算货物</div>
        </template>
      </cy-info-title>
      <div class="table-box" style="width: 100%">
        <el-table
          :data="goodsInfoList"
          :span-method="combineRow"
        >
          <el-table-column type="index" label="序号" width="50" />
          <el-table-column prop="settlementNumber" label="结算单号">
            <template slot-scope="scope">
              <el-tooltip class="item" effect="dark" :content="scope.row.settlementNumber" placement="top">
                <span class="one-ellipsis">{{ scope.row.settlementNumber }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="goodsName" label="名称" label-class-name="rule-required">
            <template slot-scope="scope">
              <el-tooltip class="item" effect="dark" :content="scope.row.goodsName" placement="top">
                <span class="one-ellipsis">{{ scope.row.goodsName }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="goodsType" label="型号" label-class-name="rule-required">
            <template slot-scope="scope">
              <el-tooltip class="item" effect="dark" :content="scope.row.goodsType" placement="top">
                <span class="one-ellipsis">{{ scope.row.goodsType }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="goodsUnit" label="单位" label-class-name="rule-required">
            <template slot-scope="scope">
              <el-tooltip class="item" effect="dark" :content="scope.row.goodsUnit" placement="top">
                <span class="one-ellipsis">{{ scope.row.goodsUnit }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="goodsQuantity" label="数量">
            <template slot-scope="scope">
              <el-tooltip class="item" effect="dark" :content="String(scope.row.goodsQuantity)" placement="top">
                <span class="one-ellipsis">{{ fourMoney(scope.row.goodsQuantity) }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="salesPrice" label="销售单价">
            <template slot-scope="scope">
              <el-tooltip class="item" effect="dark" :content="String(scope.row.salesPrice)" placement="top">
                <span class="one-ellipsis">{{ formatMoney(scope.row.salesPrice) }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="salesTotalPrice" label="销售总价">
            <template slot-scope="scope">
              <el-tooltip class="item" effect="dark" :content="String(scope.row.salesTotalPrice)" placement="top">
                <span class="one-ellipsis">{{ formatMoney(scope.row.salesTotalPrice) }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="usedNum" label="已开票数量">
            <template slot-scope="scope">
              <el-tooltip class="item" effect="dark" :content="String(scope.row.usedNum)" placement="top">
                <span class="one-ellipsis">{{ fourMoney(scope.row.usedNum) }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="openQuantity" label="本次开票数量" label-class-name="rule-required">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.openQuantity"
                placeholder="请输入本次开票数量"
                :disabled="disabled"
                @blur="calcMoney(scope.row,scope.$index)"
                @input="totalOpenQuantity(scope.row,scope.$index)"
              />
            </template>
          </el-table-column>
          <el-table-column prop="openAmount" label="本次开票金额">
            <template slot-scope="scope">
              <el-tooltip class="item" effect="dark" :content="calcMoney(scope.row,scope.$index)" placement="top">
                <span class="one-ellipsis">{{ calcMoney(scope.row,scope.$index) }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column v-if="!disabled" label="操作">
            <template slot-scope="scope">
              <span style="color: #FE7D0B; cursor: pointer;" @click="deleteInfo(scope.$index)">删除</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <cy-dialog ref="dialog" title="选择结算单">
        <cy-comm-table
          ref="commTable"
          v-loading="settlementLoading"
          :columns="columns"
          :table-options="tableOptions"
          :data="settlementData"
          :count="total"
        />
        <div class="submit-btn">
          <el-button type="primary" style="width: 150px;" @click="settlementSubmit">确定</el-button>
          <el-button style="width: 150px;" @click="() => { $refs.dialog.show = false }">取消</el-button>
        </div>
      </cy-dialog>
      <!-- <cy-info-title style="margin-bottom:20px">
        <span>
          采购发票
          <span class="statistics">数量合计： <span>{{ fourMoney(nvoiceNumTotal) }}</span></span>
          <span class="statistics">金额合计： <span>{{ formatMoney(amountTotal) }}</span></span>
          <span class="statistics">税额合计： <span>{{ formatMoney(taxAmountTotal) }}</span></span>
          <span class="statistics">价税合计： <span>{{ formatMoney(priceTaxTotalTotal) }}</span></span>
        </span>
        <template v-if="!disabled" slot="right">
          <span style="color: #FE7D0B; margin-right: 20px; cursor: pointer" @click="addInfo">添加</span>
          <span style="color: #FE7D0B; margin-right: 20px; cursor: pointer" @click="view">示例</span>
        </template>
      </cy-info-title> -->
      <!-- <div class="table-box" style="width: 100%">
        <el-table :data="procureList">
          <el-table-column type="index" label="序号" width="50" />
          <el-table-column prop="nvoiceNumber" label="发票号码" label-class-name="rule-required">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.nvoiceNumber"
                placeholder="请输入发票号码"
                :disabled="disabled"
              />
            </template>
          </el-table-column>
          <el-table-column prop="nvoiceNum" label="数量" label-class-name="rule-required">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.nvoiceNum"
                placeholder="请输入数量"
                :disabled="disabled"
              />
            </template>
          </el-table-column>
          <el-table-column prop="amount" label="金额" label-class-name="rule-required">
            <template slot-scope="scope">
              <cy-amount-input
                v-model="scope.row.amount"
                placeholder="请输入金额"
                :disabled="disabled"
              />
            </template>
          </el-table-column>
          <el-table-column prop="taxAmount" label="税额" label-class-name="rule-required">
            <template slot-scope="scope">
              <cy-amount-input
                v-model="scope.row.taxAmount"
                placeholder="请输入税额"
                :disabled="disabled"
              />
            </template>
          </el-table-column>
          <el-table-column prop="priceTaxTotal" label="价税合计" label-class-name="rule-required">
            <template slot-scope="scope">
              <cy-amount-input
                v-model="scope.row.priceTaxTotal"
                placeholder="请输入价税合计"
                :disabled="disabled"
              />
            </template>
          </el-table-column>
          <el-table-column prop="sellerName" label="销售方名称" label-class-name="rule-required">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.sellerName"
                placeholder="请输入销售方名称"
                :disabled="disabled"
              />
            </template>
          </el-table-column>
          <el-table-column v-if="!disabled" label="操作">
            <template slot-scope="scope">
              <span style="color: #FE7D0B; cursor: pointer;" @click="deleteInfo(scope.$index)">删除</span>
            </template>
          </el-table-column>
        </el-table>
      </div> -->
      <el-form-item label="开票明细表（含税收分类编码）" prop="invoiceDetailFiles" class="form-required">
        <!-- <el-input
          v-model="ruleForm.productBroadInfo"
          placeholder="请输入商品大类信息"
          :disabled="disabled"
        /> -->
        <cy-upload
          ref="invoiceDetailFiles"
          :upload-params="{
            fileType: 'invoiceDetailFile'
          }"
          :file-data="ruleForm.invoiceDetailFiles"
          :upload-from-orange-status="true"
          placeholder="请上传开票明细表附件"
          :disabled="disabled"
        />
      </el-form-item>
      <el-form-item
        label="采购发票附件"
        prop="invoicePurchaseFile"
        class="form-required"
      >
        <cy-upload
          ref="invoicePurchaseFile"
          :upload-params="{
            fileType: 'invoicePurchaseFile'
          }"
          :file-data="ruleForm.invoicePurchaseFile"
          :upload-from-orange-status="true"
          placeholder="请上传采购发票附件"
          :disabled="disabled"
        />
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
// import { getSaleSelectGoodsOfPayment } from '@/api/mySettlement/invoicesManagement'
import { fourMoney, formatMoney } from '@/utils/index'
import { mapGetters } from 'vuex'
export default {
  components: {
    BasicInformation: () => import('./BasicInformation.vue')
  },
  // mixins: [indexTable, procureTable],
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    deatilsInfo: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      key: 0,
      goodsInfoList: [],
      settlementData: [],
      multipleSelection: [],
      businessNumber: '',
      page: 1,
      size: 10,
      total: 20,
      openAmountTotal: 0,
      openQuantityTotal: 0,
      settlementLoading: false,
      // procureList: [],
      basicDisabled: false,
      ruleForm: {
        accountBankName: '',
        accountNumber: '',
        invoiceType: '',
        amountKind: 'amount_kind_payment',
        openAmount: '',
        remark: '',
        // productBroadInfo: '',
        invoicePurchaseFile: [],
        invoiceDetailFiles: [], // 发票明细
        enterpriseName: '',
        socialCreditCode: '',
        phoneNumber: '',
        address: ''
      },
      rules: {
        address: [{ required: true, message: '请输入地址', trigger: 'blur' }],
        phoneNumber: [{ required: true, message: '请输入电话', trigger: 'blur' }],
        accountBankName: [{ required: true, message: '请输入开户行名称', trigger: 'blur' }],
        accountNumber: [{ required: true, message: '请输入开户账号', trigger: 'blur' }],
        invoiceType: [{ required: true, message: '请选择发票类型', trigger: 'change' }],
        amountKind: [{ required: true, message: '请选择金额种类', trigger: 'change' }],
        remark: [{ required: true, message: '请输入备注信息', trigger: 'blur' }]
        // productBroadInfo: [{ required: true, message: '请输入商品大类信息', trigger: 'blur' }]
      },
      findByParentCode: [],
      basicInformation: {},
      tableOptions: {
        sortTable: true,
        maxHeight: 'calc(100vh - 400px)',
        height: 'calc(100vh - 400px)'
      },
      columns: [
        {
          type: 'selection',
          single: false
        },
        {
          label: '序号',
          index: true
        },
        {
          label: '结算单编号',
          prop: 'settlementNumber',
          showTooltip: true
        },
        {
          label: '验收单编号',
          showTooltip: true,
          prop: 'acceptanceNumber'
        },
        {
          label: '结算日期',
          prop: 'settlementDate',
          width: 120,
          render: (h, row) => {
            return <div>{ row.settlementDate ? row.settlementDate.split(' ')[0] : '' }</div>
          }
        },
        {
          label: '结算状态',
          prop: 'statusName',
          width: 120
        },
        {
          label: '结算金额',
          prop: 'settlementAmount',
          showTooltip: true,
          render: (h, row) => {
            return <div>{ formatMoney(row.settlementAmount) }</div>
          }
        }
      ],
      mapInfo: {}
    }
  },
  computed: {
    ...mapGetters([
      'constant'
    ]),
    fourMoney() {
      return (val) => {
        return fourMoney(val)
      }
    },
    formatMoney() {
      return (val) => {
        return formatMoney(val)
      }
    },
    calcMoney() {
      return (val) => {
        return formatMoney(Number(val.openQuantity) * Number(val.salesPrice))
      }
    }
    // #region 贸理通4.0版本优化 发票管理
    // nvoiceNumTotal() {
    //   let sum = 0
    //   this.procureList.forEach(item => {
    //     sum += Number(item.nvoiceNum)
    //   })
    //   return sum
    // },
    // amountTotal() {
    //   let sum = 0
    //   this.procureList.forEach(item => {
    //     sum += Number(item.amount)
    //   })
    //   return sum
    // },
    // taxAmountTotal() {
    //   let sum = 0
    //   this.procureList.forEach(item => {
    //     sum += Number(item.taxAmount)
    //   })
    //   return sum
    // },
    // priceTaxTotalTotal() {
    //   let sum = 0
    //   this.procureList.forEach(item => {
    //     sum += Number(item.priceTaxTotal)
    //   })
    //   return sum
    // }
    // #endregion
  },
  watch: {
    deatilsInfo: {
      handler(newV) {
        if (this.deatilsInfo && Object.keys(newV).length) {
          const { purchContractCompletedVo, enterpriseCustomerInfoId, tradingPlatformId, companyName, taxIdentifyNumber, phone, address, accountBankName, accountNumber, invoiceType, openAmount, remark, files, invoiceGoodsInfos, invoiceDetailList } = JSON.parse(JSON.stringify(newV))
          this.basicInformation = {
            ...purchContractCompletedVo,
            enterpriseCustomerInfoId,
            tradingPlatformId
          }
          this.ruleForm = {
            enterpriseName: companyName,
            socialCreditCode: taxIdentifyNumber,
            phoneNumber: phone,
            address,
            accountBankName,
            accountNumber,
            invoiceType,
            amountKind: 'amount_kind_payment',
            openAmount,
            remark,
            // productBroadInfo,
            invoicePurchaseFile: files || [],
            invoiceDetailFiles: invoiceDetailList || []
          }
          this.goodsInfoList = invoiceGoodsInfos || []
          // this.procureList = purchaseInvoiceInfos || []
          this.totalOpenQuantity()
        }
      },
      immediate: true,
      deep: true
    }
  },
  created() {
    this.$store.dispatch('getConstant', ['invoiceType', 'amountKind'])
    const { type } = this.$route.query
    if (type === 'see') {
      this.basicDisabled = true
    }
  },
  methods: {
    getInvoiceInformation(val, businessNumber) {
      this.invoiceInformation = val
      this.ruleForm = {
        enterpriseName: val.enterpriseName,
        socialCreditCode: val.socialCreditCode,
        phoneNumber: val.phoneNumber,
        address: val.address,
        invoiceType: '',
        amountKind: 'amount_kind_payment',
        accountBankName: val.accountBankName || '',
        accountNumber: val.accountNumber || '',
        remark: val.remark || ''
      }
      this.businessNumber = businessNumber
    },
    select(type) {
      if (type === 'selectGoods') {
        this.$refs.dialog.show = true
        this.settlementLoading = true
        // const params = {
        //   page: this.page,
        //   rows: this.size,
        //   businessNumber: this.businessNumber
        // }
        // getSaleSelectGoodsOfPayment(params).then(data => {
        //   this.settlementData = data.data.rows
        //   this.$nextTick(() => {
        //     this.settlementData.forEach(item => {
        //       if (this.goodsInfoList.some(row => row.settlementBasicInfoId === item.id)) {
        //         this.$refs.commTable.toggleRowSelection([item])
        //       }
        //     })
        //   })
        //   this.settlementLoading = false
        // })
      }
    },
    settlementSubmit() {
      this.$refs.dialog.show = false
      this.goodsInfoList = []
      const goodsInfo = []
      this.multipleSelection = this.$refs.commTable.multipleSelection
      // let arr = []
      // this.mapInfo = new Map()
      // this.multipleSelection.forEach(item => {
      //   arr = [...arr, ...item.invoiceGoodsInfos]
      //   const obj = {
      //     start: arr.length - 1,
      //     end: item.invoiceGoodsInfos.length,
      //     length: item.invoiceGoodsInfos.length
      //   }
      //   this.mapInfo.set(item.id, obj)
      // })
      this.multipleSelection.map((item, index) => {
        // this.goodsInfoList = [...this.goodsInfoList, ...item.invoiceGoodsInfos]
        if (item.invoiceGoodsInfos) {
          const len = item.invoiceGoodsInfos.length
          item.invoiceGoodsInfos.forEach((item, index) => {
            if (index === 0) {
              item.length = len
            }
            goodsInfo.push(item)
          })
        }
      })
      this.goodsInfoList = goodsInfo
      this.totalOpenQuantity()
    },
    combineRow({ row, columnIndex }) {
      const merge = row.length ? row.length : 0
      const _colMerge = merge > 0 ? 1 : 0
      if (columnIndex === 11) {
        return {
          rowspan: merge,
          colspan: _colMerge
        }
      }
    },
    totalOpenQuantity() {
      let sum = 0; let amount = 0
      this.goodsInfoList.forEach((item, index) => {
        sum += Number(item.openQuantity)
        item.openAmount = item.openQuantity * item.salesPrice
        amount += Number(item.openAmount)
      })
      this.openQuantityTotal = sum
      this.openAmountTotal = amount
      this.ruleForm.openAmount = formatMoney(amount)
    },
    // #region comment by lx 贸理通4.0版本优化发票管理
    // addInfo() {
    //   this.procureList.push({
    //     nvoiceNumber: '',
    //     nvoiceNum: '',
    //     amount: '',
    //     taxAmount: '',
    //     priceTaxTotal: '',
    //     sellerName: ''
    //   })
    // },
    // view() {

    // },
    // #endregion
    getParams() {
      return new Promise((resolve, reject) => {
        // if (!this.goodsInfoList.length) {
        //   this.$message.warning('请添加货物信息')
        //   return
        // }
        // for (let i = 0; i < this.goodsInfoList.length; i++) {
        //   const { goodsName, goodsFactory, modelNumber, units, quantity, clearPrice, salesPrice } = this.goodsInfoList[i]
        //   if (!goodsName) {
        //     this.$message.warning('请输入姓名')
        //     return
        //   }
        //   if (!goodsFactory) {
        //     this.$message.warning('请输入厂家')
        //     return
        //   }
        //   if (!modelNumber) {
        //     this.$message.warning('请输入型号')
        //     return
        //   }
        //   if (!units) {
        //     this.$message.warning('请输入单位')
        //     return
        //   }
        //   if (!quantity) {
        //     this.$message.warning('请输入数量')
        //     return
        //   }
        //   if (clearPrice === '') {
        //     this.$message.warning('请选择是否明确单价')
        //     return
        //   }
        //   if (clearPrice === 1) {
        //     if (!salesPrice) {
        //       this.$message.warning('请输入销售单价')
        //       return
        //     }
        //   }
        // }
        const { enterpriseName, socialCreditCode, address, phoneNumber, invoiceType, amountKind, openAmount, remark, accountBankName, accountNumber } = this.ruleForm
        const invoicePurchaseFileList = this.$refs.invoicePurchaseFile.getFileLists
        const invoiceDetailFileList = this.$refs.invoiceDetailFiles.getFileLists
        const { id, taskId } = this.$route.query
        this.$refs.basicInformation.getParams().then(item => {
          const params = {
            ...item,
            id,
            taskId,
            companyName: enterpriseName,
            taxIdentifyNumber: socialCreditCode,
            address,
            phone: phoneNumber,
            accountBankName,
            accountNumber,
            invoiceType,
            amountKind,
            openAmount,
            remark,
            // productBroadInfo,
            // purchaseInvoiceInfos: this.procureList,
            purchaseInvoiceFiles: invoicePurchaseFileList.map(item => item.id),
            invoiceDetailFiles: invoiceDetailFileList.map(item => item.id),
            invoiceGoodsInfos: this.goodsInfoList
          }
          resolve(params)
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.apply-invoicing-content {

}
</style>
