<script setup name="fillContractInfo">
import { getCurrentInstance, ref, onMounted } from 'vue'
import { changFilesParam, fileFormatVerification, handleFileSuccess, reviewFileParam, fileTypes, fileDesc, handleFilePreview } from '@/utils/uploadAction.js'
import store from '@/store'
import { useRouter, useRoute } from 'vue-router'
import { contractDetail, submitContract, supplement } from '@/http/apis/declareMange/contractRecord'

const uploadUrl = store.dictStore.uploadUrl,
  { proxy } = getCurrentInstance(),
  router = useRouter(),
  route = useRoute()
const formRef = ref(),
  moneyValidator = (rule, value, callback) => {
    if (!value) callback()
    if (!/^\d+(\.\d{1,6})?$/.test(value)) {
      callback('请输入正确格式，最多保留六位小数')
    } else if (value * 1 >= 100000000) {
      callback('请输入正确格式，小于100000000')
    } else {
      callback()
    }
  },
  rules = {
    name: [{ required: true, message: '请输入合同名称' }],
    totalAmount: [{ required: true, message: '请输入合同总金额' }, { validator: moneyValidator, trigger: 'blur' }],
    supplierBank: [{ required: true, message: '请输入供应商收款开户行' }],
    supplierAccount: [{ required: true, message: '请输入供应商收款账号' }],
    warrantyPeriod: [{ required: true, message: '请输入质保期' }],
    retentionMoney: [{ required: true, message: '请输入质保金' }, { validator: moneyValidator, trigger: 'blur' }],
    contractTime: [{ required: true, message: '请选择合同签订完成时间' }],
    deliveryTime: [{ required: true, message: '请选择交货日期' }],
    attachment: [{ required: true, message: '请上传合同附件' }]
  },
  formData = ref({
    attachment: [],
    payments: []
  }),
  // 付款计划
  column = ref([
    {
      label: '付款笔数',
      key: 'number',
      slot: 'number'
    },
    {
      label: '付款计划',
      key: 'planAmount',
      slot: 'planAmount'
    },
    {
      label: '付款比例（%）',
      key: 'ratio',
      slot: 'ratio'
    },
    {
      label: '付款金额（万元）',
      key: 'paymentAmount',
      slot: 'paymentAmount'
    },
    {
      label: '预计付款时间',
      key: 'paymentTime',
      slot: 'paymentTime'
    },
    {
      label: '操作',
      key: 'action',
      slot: 'action',
      width: 80
    }
  ]),
  // 添加付款计划
  add = () => {
    formData.value.payments.push({})
  },
  // 删除付款计划
  del = (index) => {
    formData.value.payments.splice(index, 1)
  },
  // 计算付款比例
  blurMoney = (row) => {
    row.ratio = Math.floor((row.paymentAmount / formData.value.totalAmount * 1) * 100 * 100) / 100
  },
  // 提交
  submitLoading = ref(false),
  submit = async (formEl) => {
    console.log(formData.value)
    if (!formEl) {
      return
    }
    formEl.validate(async (valid, err) => {
      if (valid) {
        if (!route.query.isReplenishment) {
          if (!formData.value.payments?.length) {
            proxy.$message.warning('请至少添加一个付款计划')
            return
          }
          const totalMoney = formData.value.payments.reduce((acc, cur) => {
            return acc + cur.paymentAmount
          }, 0)
          if (totalMoney !== formData.value.totalAmount) {
            proxy.$message.warning('付款金额总和必须等于合同总金额')
            return
          }
          submitLoading.value = true
          const postData = {
            ...formData.value,
            projectId: route.query.id,
            attachment: formData.value.attachment && JSON.stringify(changFilesParam(formData.value.attachment))
          }
          try {
            await submitContract(postData)
            submitLoading.value = false
            proxy.$message.success('提交成功')
            router.go(-1)
          } catch (e) {
            submitLoading.value = false
          }
        } else {
          submitActualPaymentAmount()
        }
      }
    })
  },
  // 提交补充金额
  submitActualPaymentAmount = async () => {
    submitLoading.value = true
    try {
      const postData = []
      formData.value.payments.forEach(i => {
        if ((i.actualPaymentAmount || i.actualPaymentAmount === 0) && !i.isReplenishment) {
          postData.push({
            actualPaymentAmount: i.actualPaymentAmount,
            id: i.id,
            projectCode: i.projectCode
          })
        }
      })
      await supplement(postData)
      proxy.$message.success('提交成功')
      router.go(-1)
      submitLoading.value = false
    } catch (e) {
      submitLoading.value = false
    }
  },
  // 获取详情
  getDetail = async () => {
    const res = await contractDetail(route.query.id)
    if (res.data) {
      formData.value = {
        ...res.data,
        attachment: res.data.attachment ? reviewFileParam(JSON.parse(res.data.attachment)) : [],
        payments: res.data.payments?.map(i => {
          return {
            ...i,
            isReplenishment: !!i.actualPaymentAmount
          }
        }) || []
      }
    }
  },
  validActualPaymentAmount = (rule, value, callback, index) => {
    if (value < 0) {
      callback('实际支付金额必须大于等于0')
    } else if (index === 0) {
      if (value > formData.value.payments[index].paymentAmount) {
        callback('实际支付金额不能超过合同计划付款金额')
      }
    } else {
      let maxData = formData.value.payments[index].paymentAmount
      for (let i = 0; i < index; i++) {
        maxData += formData.value.payments[i].paymentAmount - formData.value.payments[i]?.actualPaymentAmount || 0
      }
      if (value > maxData) {
        callback(`实际支付金额不能超过${maxData}万元`)
      }
    }
    callback()
  }
onMounted(() => {
  getDetail()
  if (route.query.isReplenishment) {
    column.value = [
      {
        label: '付款笔数',
        key: 'number',
        slot: 'number'
      },
      {
        label: '付款计划',
        key: 'planAmount',
        slot: 'planAmount'
      },
      {
        label: '付款比例（%）',
        key: 'ratio',
        slot: 'ratio'
      },
      {
        label: '付款金额（万元）',
        key: 'paymentAmount',
        slot: 'paymentAmount'
      },
      {
        label: '预计付款时间',
        key: 'paymentTime',
        slot: 'paymentTime'
      },
      {
        label: '实际支付金额（万元）',
        key: 'actualPaymentAmount',
        slot: 'actualPaymentAmount',
        width: 180
      }
    ]
  }
})
</script>
<template>
  <div class="fillPurchasingResult footerPage">
    <el-card class="w-full">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-position="right"
        label-width="180px"
        label-suffix=":"
        scroll-to-error
      >
        <el-row :gutter="40">
          <el-col :span="12">
            <el-form-item label="合同名称" prop="name">
              <el-input
                v-model="formData.name"
                maxlength="50"
                placeholder="请输入"
                :disabled="!!$route.query.isReplenishment"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同总金额" prop="totalAmount">
              <el-input
                v-model.number="formData.totalAmount"
                placeholder="请填写"
                :disabled="!!$route.query.isReplenishment"
              >
                <template #suffix>万元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商收款开户行" prop="supplierBank">
              <el-input
                v-model="formData.supplierBank"
                maxlength="50"
                placeholder="请输入"
                :disabled="!!$route.query.isReplenishment"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商收款账号" prop="supplierAccount">
              <el-input
                v-model="formData.supplierAccount"
                maxlength="50"
                placeholder="请输入"
                :disabled="!!$route.query.isReplenishment"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="质保期" prop="warrantyPeriod">
              <el-input
                v-model="formData.warrantyPeriod"
                maxlength="50"
                placeholder="请输入"
                :disabled="!!$route.query.isReplenishment"
                @input="formData.warrantyPeriod=formData.warrantyPeriod?.replace(/[^\d]/g,'')"
              >
                <template #suffix>
                  年
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="质保金" prop="retentionMoney">
              <el-input
                v-model.number="formData.retentionMoney"
                placeholder="请填写"
                :disabled="!!$route.query.isReplenishment"
              >
                <template #suffix>万元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="合同签订完成时间"
              prop="contractTime"
            >
              <el-date-picker
                v-model="formData.contractTime"
                type="date"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                placeholder="请选择"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="交货日期"
              prop="deliveryTime"
            >
              <el-date-picker
                v-model="formData.deliveryTime"
                type="date"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                placeholder="请选择"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="合同附件" prop="attachment">
              <el-upload
                v-model:file-list="formData.attachment"
                class="w-full"
                :action="uploadUrl"
                :on-success="res => handleFileSuccess(res, formData.attachment)"
                :before-upload="file=>fileFormatVerification(file, {types: fileTypes})"
                :accept="fileTypes.map(i=>`.${i}`).join(',')"
                :on-preview="handleFilePreview"
              >
                <el-button type="primary" plain>选择文件</el-button>
                <template #tip>
                  <div class="el-upload__tip">
                    支持{{ fileDesc }}文件
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <table-list
              ref="tableListRef"
              :column="column"
              :data="formData.payments"
              :pagination="false"
              :empty-temp="false"
            >
              <template #number="{scope}">
                <span>第{{ scope.$index+1 }}笔</span>
              </template>
              <template #planAmount="{scope}">
                <el-form-item
                  v-if="scope.$index>=0"
                  :prop="`payments[${scope.$index}].planAmount`"
                  :rules="[{ required: true, message: '请输入' }]"
                  label-width="0"
                  style="margin-bottom: 0"
                >
                  <el-input
                    v-model="scope.row.planAmount"
                    placeholder="请填写"
                    :disabled="!!$route.query.isReplenishment"
                  />
                </el-form-item>
              </template>
              <template #ratio="{scope}">
                <el-form-item
                  v-if="scope.$index>=0"
                  :prop="`payments[${scope.$index}].ratio`"
                  :rules="[{ required: true, message: '请输入' }]"
                  label-width="0"
                  style="margin-bottom: 0"
                >
                  <el-input v-model.number="scope.row.ratio" placeholder="自动计算" disabled />
                </el-form-item>
              </template>
              <template #paymentAmount="{scope}">
                <el-form-item
                  v-if="scope.$index>=0"
                  :prop="`payments[${scope.$index}].paymentAmount`"
                  :rules="[{ required: true, message: '请输入' }]"
                  label-width="0"
                  style="margin-bottom: 0"
                >
                  <el-input-number
                    v-model="scope.row.paymentAmount"
                    placeholder="请填写"
                    :min="0"
                    :controls="false"
                    :disabled="!!$route.query.isReplenishment"
                    @mousewheel.prevent
                    @blur="blurMoney(scope.row)"
                  />
                </el-form-item>
              </template>
              <template #paymentTime="{scope}">
                <el-form-item
                  v-if="scope.$index>=0"
                  :prop="`payments[${scope.$index}].paymentTime`"
                  :rules="[{ required: true, message: '请选择' }]"
                  label-width="0"
                  style="margin-bottom: 0"
                >
                  <el-date-picker
                    v-model="scope.row.paymentTime"
                    type="date"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    placeholder="请选择"
                    :disabled="!!$route.query.isReplenishment"
                  />
                </el-form-item>
              </template>
              <template #action="{scope}">
                <a class="text-danger" @click="del(scope.$index)">删除</a>
              </template>
              <template #actualPaymentAmount="{scope}">
                <el-form-item
                  v-if="scope.$index>=0"
                  label-width="0"
                  :prop="`payments[${scope.$index}].actualPaymentAmount`"
                  :rules="[{ validator: (rule,value,callback)=>validActualPaymentAmount(rule,value,callback,scope.$index)}]"
                  style="margin-bottom: 25px;margin-top: 20px"
                >
                  <el-input-number
                    v-model="scope.row.actualPaymentAmount"
                    placeholder="请填写"
                    :min="0"
                    :controls="false"
                    :disabled="scope.row.isReplenishment"
                    @mousewheel.prevent
                  />
                </el-form-item>
              </template>
            </table-list>
            <el-button
              v-if="!$route.query.isReplenishment"
              type="primary"
              icon="Plus"
              plain
              class="w-full mt-8"
              @click="add"
            >添加付款计划</el-button>
            <p v-if="$route.query.isReplenishment" class="text-danger text-14">温馨提示：请谨慎填写实际支付金额，填写后不允许修改</p>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <div class="footer">
      <el-button @click="router.go(-1)"> 返回 </el-button>
      <el-button type="primary" :loading="submitLoading" @click="submit(formRef)"> 提交 </el-button>
    </div>
  </div>
</template>
