<template>
  <el-dialog v-model="showDialog" title="尾款打款审批" width="1200px" @close="closeDialog">
    <div v-loading="loading">
      <div class="h5Tit">商品信息</div>
      <el-table :data="goodsList" style="width: 100%;margin-top: 15px;" border>
        <el-table-column prop="goods.title" label="商品名称" />
        <el-table-column label="规格名称">
          <template #default="scope">
            <span>{{ scope.row.sku && scope.row.sku.title || scope.row.title }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="unit" label="单位" align="center" />
        <el-table-column prop="expect_unit_price" label="预计产品单价（含税）" align="center" />
        <el-table-column label="实际产品单价（含税）" align="center">
          <template #default="scope">
            <el-input class="inpt" type="text" v-model="scope.row.real_unit_price" @input="changeInput" />
          </template>
        </el-table-column>
        <el-table-column prop="expect_quantity" label="预计采购数量" align="center" />
        <el-table-column label="实际采购数量" align="center">
          <template #default="scope">
            <el-input class="inpt" type="text" v-model="scope.row.real_quantity" @input="changeInput" />
          </template>
        </el-table-column>
        <el-table-column prop="expect_amount" label="预计订单金额" align="center" />
        <el-table-column prop="real_amount" label="实际订单金额" align="center" />
        <el-table-column prop="has_paid_amount" label="已打款" align="center" />
        <el-table-column label="申请打款金额" align="center">
          <template #default="scope">
            <el-input type="text" class="inpt" v-model="scope.row.apply_amount" @input="changeApply" />
          </template>
        </el-table-column>
      </el-table>
      
      <div class="h5Tit">其他费用</div>
      <el-button type="primary" @click="addFee">添加其他费用</el-button>
      <el-table :data="feesList" style="width: 100%;margin-top: 15px;" border>
        <el-table-column label="费用名称" align="center">
          <template #default="scope">
           <div style="display: flex;align-items: center;white-space: nowrap;">
            <el-input type="text" v-model="scope.row.fee_name" :disabled="scope.row.id" />
            <span style="color: #f00;" v-if="scope.row.has_paid_amount * 1 == 0">&nbsp;&nbsp;已驳回</span>
           </div>
          </template>
        </el-table-column>
        <el-table-column label="订单金额">
          <template #default="scope">
            <el-input type="text" v-model="scope.row.amount" :disabled="scope.row.id" />
          </template>
        </el-table-column>
        <el-table-column label="打款信息">
          <template #default="scope">
            <el-select v-model="scope.row.other_expense_account_id" placeholder="请选择" clearable filterable :disabled="scope.row.id">
              <el-option v-for="it in accountList" :key="it.id" :label="it.name" :value="it.id" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="100">
          <template #default="scope">
            <el-button type="danger" :disabled="scope.row.id" size="mini" @click="removeFee(scope.$index)"><el-icon><DeleteFilled /></el-icon></el-button>
          </template>
        </el-table-column>
      </el-table>

      <div style="padding: 20px 0;color: #f00;">合计申请打款金额：{{total_amount}}元</div>

      <div class="huibox">
        <div>
          打款前：总实际订单金额（元）：{{itemInfo.total_amount}}，
          总实际已支付金额（元）：{{itemInfo.has_paid_amount}}，
          总实际未支付金额（元）：{{ ((itemInfo.total_amount * 100 - itemInfo.has_paid_amount * 100) / 100).toFixed(2) }}
        </div>
        <div>
          打款后：总实际订单金额（元）：{{real_total_amount}}，
          总实际已支付金额（元）：{{ ((itemInfo.has_paid_amount * 100 + total_amount * 100) / 100).toFixed(2) }}，
          总实际未支付金额（元）：{{ ((real_total_amount * 100 - itemInfo.has_paid_amount * 100 - total_amount * 100) / 100).toFixed(2) }}
        </div>
      </div>
    </div>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeDialog()">取消</el-button>
        <el-button type="primary" @click="commitApproval()" :loading="btnloading">提交审批</el-button>
      </span>
    </template>
  </el-dialog>

</template>

<script>
import { DeleteFilled, Search } from "@element-plus/icons"
import { reactive, toRefs, watch } from 'vue'
import { get, post } from '@/api/request'
import { ElMessage } from 'element-plus'

export default {
  components: { DeleteFilled, Search },
  props: {
    show: {
      type: Boolean,
      default: false
    },
    id: {
      type: Number,
      default: 0,
    }
  },
  setup(props, context) {
    const data = reactive({
      launchId: 0,
      showDialog: false,
      accountList: [],
      goodsList: [],
      loading: false,
      feesList: [],
      btnloading: false,
      total_amount: 0,
      real_total_amount: 0,
      itemInfo: {}
    })

    function getDetail() {
      data.loading = true
      get(`/api/purchaseOrder/${data.launchId}`).then((res) => {
        data.itemInfo = res.data
        data.feesList = res.data.other_expenses
        data.goodsList = res.data.products
        data.loading = false
      }).catch(() => {
        data.loading = false
      })
    }
    
    function getAccount() {
      get(`/api/otherExpenseAccount`, {page: 1, pageSize: 1000}).then((res) => {
        data.accountList = res.data
      })
    }

    const commitApproval = () => {
      data.btnloading = true
      let products = []
      for (let index = 0; index < data.goodsList.length; index++) {
        let obj = data.goodsList[index]
        products.push({
          id: obj.id,
          product_id: obj.product_id,
          sku_id: obj.id,
          real_unit_price: obj.real_unit_price,
          real_quantity: obj.real_quantity,
          apply_amount: obj.apply_amount
        })
      }
      let params = {
        purchase_order_id: data.launchId,
        products: products,
        otherExpenses: data.feesList
      }
      post(`/api/purchaseOrder/finalPaymentSubmit`, params).then((res) => {
        ElMessage({ type: 'success', message: '提交成功' })
        closeDialog()
        context.emit('refresh')
        data.btnloading = false
      }).catch(() => {
        data.btnloading = false
      })
    }

    function clearForm() {
      data.feesList = []
      data.goodsList = []
    }

    const closeDialog = () => {
      clearForm()
      context.emit('close')
      data.showDialog = false
    }

    function addFee() {
      data.feesList.push({
        fee_name: '',
        amount: '',
        other_expense_account_id: ''
      })
    }

    function removeFee(i) {
      data.feesList.splice(i, 1)
    }

    function getTotalAmount() {
      let num = 0, total = 0
      for (let index = 0; index < data.goodsList.length; index++) {
        let item = data.goodsList[index]
        let real_amount = item.real_unit_price * item.real_quantity
        total += real_amount * 100
        if(item.apply_amount) {
          num += item.apply_amount * 100
        } else if(item.real_unit_price && item.real_quantity) {
          num += real_amount * 100 - item.has_paid_amount * 100
        }
      }
      for (let index = 0; index < data.feesList.length; index++) {
        let item = data.feesList[index]
        if(item.amount) {
          if((item.has_paid_amount * 1 > 0 && item.id) || !item.id) {
            total += item.amount * 100
          }
          if(!item.id) {
            num += item.amount * 100
          }
        }
      }
      data.total_amount = (num / 100).toFixed(2)
      data.real_total_amount = (total / 100).toFixed(2)
    }

    function changeInput(){
      for (let index = 0; index < data.goodsList.length; index++) {
        let item = data.goodsList[index]
        if(item.real_unit_price && item.real_quantity) {
          item.real_amount = item.real_unit_price * item.real_quantity
          item.apply_amount = ((item.real_amount * 100 - item.has_paid_amount * 100) / 100).toFixed(2)
        }
      }
      getTotalAmount()
    }

    function changeApply() {
      let num = 0, total = 0
      for (let index = 0; index < data.goodsList.length; index++) {
        let item = data.goodsList[index]
        num += item.apply_amount * 100
        let real_amount = item.real_unit_price * item.real_quantity
        total += real_amount * 100
      }
      for (let index = 0; index < data.feesList.length; index++) {
        let item = data.feesList[index]
        if(item.amount) {
          if((item.has_paid_amount * 1 > 0 && item.id) || !item.id) {
            total += item.amount * 100
          }
          if(!item.id) {
            num += item.amount * 100
          }
        }
      }
      data.total_amount = (num / 100).toFixed(2)
      data.real_total_amount = (total / 100).toFixed(2)
    }

    watch(() => data.feesList, (newProps) => {
      getTotalAmount()
    }, { deep: true })

    watch(() => props, (newProps) => {
      if (newProps.show) {
        data.showDialog = true
        data.launchId = newProps.id
        if(data.launchId) {
          getDetail()
        }
        getAccount()
      }
    }, { deep: true })

    return {
      ...toRefs(data),
      changeInput,
      getDetail,
      getAccount,
      closeDialog,
      clearForm,
      commitApproval,
      addFee,
      removeFee,
      getTotalAmount,
      changeApply
    }
  }
}
</script>

<style scoped lang="scss">
  ::v-deep .inpt .el-input__inner{
    text-align: center;
  }
  .h5Tit{
    margin-top: 20px;
  }
  .huibox{
    background-color: #f5f5f5;
    padding: 15px;
    line-height: 30px;
    border-left: 3px solid #3c8dbc;
  }
</style>