<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible"  width="1200px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="160px"
      v-loading="formLoading"
    >
      <el-row>


<!--      <el-form-item label="项目编号" prop="code" width="200px">-->
<!--        <el-input v-model="formData.code" placeholder="请输入项目编号" disabled   class="!w-220px"/>-->
<!--      </el-form-item>-->
      <el-form-item label="项目名称" prop="projectName">
        <el-input v-model="formData.projectName" placeholder="请输入项目名称" disabled   class="!w-230px"/>
      </el-form-item>
      <el-form-item label="生成日期" prop="cgTime" >
        <el-date-picker
          v-model="formData.cgTime"
          type="date"
          value-format="x"
          placeholder="选择生成日期" disabled
          class="!w-230px"
        />
      </el-form-item>
        <el-form-item label="客户名称" prop="cgKhname" >
          <el-input v-model="formData.cgKhname" placeholder="请输入客户名称" disabled   class="!w-230px"/>
        </el-form-item>
      </el-row>
      <el-row>
      <el-form-item label="应收金额" prop="cgYs" >
        <el-input v-model="formData.cgYs" placeholder="请输入应收金额" disabled   class="!w-230px"/>
      </el-form-item>
      <el-form-item label="已收金额" prop="cgYishou">
        <el-input v-model="formData.cgYishou" placeholder="请输入已收金额" disabled   class="!w-230px"/>
      </el-form-item>
        <el-form-item label="已开票金额" prop="amount">
          <el-input v-model="formData.amount" placeholder="请输入已开票金额" disabled   class="!w-230px"/>
        </el-form-item>
      </el-row>
      <el-row>
        <el-col :span="8" >
        <el-form-item label="回款状态" prop="cgTypee" >
          <el-select
            v-model="formData.cgTypee"
            placeholder="请选择"
            clearable

          >
            <el-option
              v-for="dict in getIntDictOptions(DICT_TYPE.HELI_YINGFU_MONEY)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        </el-col>
        <el-col :span="16">
      <el-form-item label="备注" prop="rem">
        <el-input  type="textarea" :rows='3' v-model="formData.rem" placeholder="请输入备注" />
      </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-card class="hl-card-info">
      <template #header>
        <div class="hl-card-info-icona"></div><span class="hl-card-info-text">付款比例</span>
      </template>
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="160px"
        v-loading="formLoading"
      >
      <el-row>
        <el-col :span="8">
          <el-form-item label="首付款" prop="shouFuKuan" >
            <el-input v-model="formData.shouFuKuan" placeholder="请输入" disabled  />
          </el-form-item>
        </el-col>
        <el-col :span="8">
        <el-form-item label="第二笔款" prop="twoFuKuan" >
          <el-input v-model="formData.twoFuKuan" placeholder="请输入" disabled   />
        </el-form-item>
        </el-col>
        <el-col :span="8">
        <el-form-item label="第三笔款" prop="threeFuKuan" >
          <el-input v-model="formData.threeFuKuan" placeholder="请输入" disabled   />
        </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
        <el-form-item label="第四笔款" prop="fourFuKuan" >
          <el-input v-model="formData.fourFuKuan" placeholder="请输入" disabled   />
        </el-form-item>
        </el-col>
        <el-col :span="8">
        <el-form-item label="第五笔款" prop="fiveFuKuan" >
          <el-input v-model="formData.fiveFuKuan" placeholder="请输入" disabled  />
        </el-form-item>
        </el-col>
        <el-col :span="8">
        <el-form-item label="第六笔款" prop="sixFuKuan" >
          <el-input v-model="formData.sixFuKuan" placeholder="请输入" disabled   />
        </el-form-item>
        </el-col>
      </el-row>
      </el-form>
    </el-card>
    <el-card class="hl-card-info">
      <template #header>
        <div class="hl-card-info-icona"></div><span class="hl-card-info-text">回款明细信息</span>
      </template>
      <el-row>
        <el-col>
          <el-card class="hl-incard">
            <el-col>
              <el-button  type="primary" size="large" @click="onAddItem" v-if="formData.cgTypee==2||formData.cgTypee==3">新增</el-button>
            </el-col>
            <el-form ref="OrderYsDetailSubFormRef" :model="formData.orderYsDetails"   label-width="0"  >
              <el-table :data="formData.orderYsDetails" class="hl-table" >
                <el-table-column type="index" label="序号" align="center" min-width="60" fixed />
                <el-table-column min-width="150" align="center">
                  <template #header> <span class="hl-table_header">*</span>回款日期 </template>
                  <template #default="scope">
                    <el-form-item  prop="paymentDate" >
                      <el-date-picker :disabled="scope.row.id"
                        v-model="scope.row.paymentDate"
                        type="date"
                        value-format=""
                        placeholder="选择回款日期"
                      />
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column min-width="150"  align="center">
                  <template #header> <span class="hl-table_header">*</span>回款类型 </template>

                  <template #default="scope">
                    <el-form-item prop="cgType" >
                      <el-select
                        v-model="scope.row.cgType" :disabled="scope.row.id"
                        placeholder="请选择"
                        clearable
                        @change="getGradeCost" >
                        <el-option
                          v-for="dict in getIntDictOptions(DICT_TYPE.HELI_CGTYPE)"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        />
                      </el-select>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column min-width="180" align="center">
                  <template #header> <span class="hl-table_header">*</span>回款金额 </template>
                  <template #default="scope">
                    <el-form-item prop="cgYishou" >
                      <el-input v-model="scope.row.cgYishou" type="number" placeholder="请输入回款金额" @change="sum" :disabled="scope.row.id" min="0" />
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="120" fixed="right">
                  <template #default="scope">
                    <el-button link type="danger" size="small" @click.prevent="onDeleteItem(scope.$index)" v-if="formData.cgTypee==2||formData.cgTypee==3">
                      删除
                    </el-button>
                    <el-button link type="primary" size="small" @click.prevent="invoices(scope.row.id)" >
                      开票
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <!-- 分页 -->

            </el-form>
          </el-card>
          </el-col>
        </el-row>
      </el-card>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </template>
  </Dialog>
  <Invoivce ref="formRefs" @success="getList" />

</template>
<script setup lang="ts">
import * as OrderYsApi from '@/api/heli/orderys'
import * as OrderYsDetailApi from '@/api/heli/orderysdetail'
import {DICT_TYPE, getIntDictOptions, getStrDictOptions} from "@/utils/dict";
import Invoivce from "@/views/heli/orderys/invoivce.vue";
import {ref} from "vue";
import * as InvoiceApi from "@/api/heli/invoice";

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const formRefs = ref()
const ids = ref()
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  id:undefined,
  type:undefined,
})
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  code: undefined,
  projectName: undefined,
  cgTime: undefined,
  cgKhname: undefined,
  cgYs: undefined,
  cgYishou: 0,
  cgTypee: undefined,
  orderYsDetails: [],
  rem: undefined,
  amount:undefined,
  shouFuKuan:undefined,
  twoFuKuan:undefined,
  threeFuKuan:undefined,
  fourFuKuan:undefined,
  fiveFuKuan:undefined,
  sixFuKuan:undefined
})
// const subFormRules = reactive({
//   paymentDate: [{
//     required: true,
//     message: '回款日期不能为空',
//     trigger: 'blur'
//   }],
//   cgType: [{
//     required: true,
//     message: '回款类型不能为空',
//     trigger: 'change'
//   }],
//   cgYishou: [{
//     required: true,
//     message: '回款金额不能为空',
//     trigger: 'blur'
//   }]
// })
const formRules = reactive({
})
const formRef = ref() // 表单 Ref
const OrderYsDetailSubFormRef = ref()
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  ids.value=id
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await OrderYsApi.getOrderYs(id)
      formData.value.orderYsDetails= await OrderYsDetailApi.getOrderYsDetails(id)
      formData.value.orderYsDetails.map(o=>{
        o.cgType=Number( o.cgType)
        let date = new Date();
        date.setFullYear(o.paymentDate[0]);
        date.setMonth(o.paymentDate[1]-1);
        date.setDate(o.paymentDate[2]);
        o.paymentDate=date
      })
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗
/** 新增子项按钮操作 */
const onAddItem = () => {
  const row = {
    id: undefined,
    cgYishou: undefined,
    paymentDate:new Date(),
    cgType: undefined,
    cgId: undefined,
  }
    row.cgId = formData.value.id

  formData.value.orderYsDetails.push(row)
}
/** 删除子项操作 */
const onDeleteItem = async (index) => {
    if (index!=formData.value.orderYsDetails.length-1){
      message.error(`请从最后一条数据开始删除`)
      return false
    }
  let id = formData.value.orderYsDetails[index].id;
  if (id){
    queryParams.id=id
    queryParams.type="FINANCE_MAKE_INVOICE"
    const data=await InvoiceApi.getInvoicePages(queryParams)
    if (data.total>0){
      message.error(`该回款已开票,不允许删除`)
      return false
    }
    await OrderYsDetailApi.deleteOrderYsDetail(id)
  }
  formData.value.orderYsDetails.splice(index, 1)
  formData.value.cgYishou=formData.value.orderYsDetails.reduce((sum, item) => sum + Number(item.cgYishou), 0);
}

const invoices = async (id) => {
  formRefs.value.open(id,formData.value.projectId,formData.value.projectCode)
}

const getList = async () => {
  formLoading.value = true
  try {
    formData.value = await OrderYsApi.getOrderYs(ids.value)
    formData.value.orderYsDetails= await OrderYsDetailApi.getOrderYsDetails(ids.value)
    formData.value.orderYsDetails.map(o=>{
      o.cgType=Number( o.cgType)
      let date = new Date();
      date.setFullYear(o.paymentDate[0]);
      date.setMonth(o.paymentDate[1]-1);
      date.setDate(o.paymentDate[2]);
      o.paymentDate=date
    })
  } finally {
    formLoading.value = false
  }
}
const sum = async () => {
  formData.value.cgYishou=formData.value.orderYsDetails.reduce((sum, item) => sum + Number(item.cgYishou), 0);
}
/** 提交表单 */
const emit = defineEmits(['success'])  // 定义 success 事件，用于操作成功后的回调
const cancel = async () => {
  dialogVisible.value = false
  emit('success')

}
const submitForm = async () => {
  // 校验表单
  // await formRef.value.validate()
  // await OrderYsDetailSubFormRef.value.validate()
  for (let i = 0; i < formData.value.orderYsDetails.length; i++) {
    if (formData.value.orderYsDetails[i].paymentDate==null){
      message.error('第'+(i+1)+'行回款日期不能为空')
      return false
    }
    if (formData.value.orderYsDetails[i].cgType==null){
      message.error('第'+(i+1)+'行回款类型不能为空')
      return false
    }
    if (formData.value.orderYsDetails[i].cgYishou==null){
      message.error('第'+(i+1)+'行回款金额不能为空')
      return false
    }

  if (formData.value.orderYsDetails[i].cgType==1&&formData.value.shouFuKuan==null){
    message.error('付款类型跟订单不一致,不允许添加')
    return false
  }
  if (formData.value.orderYsDetails[i].cgType==2&&formData.value.twoFuKuan==null){
    message.error('付款类型跟订单不一致,不允许添加')
    return false
  }
  if (formData.value.orderYsDetails[i].cgType==3&&formData.value.threeFuKuan==null){
    message.error('付款类型跟订单不一致,不允许添加')
    return false
  }
  if (formData.value.orderYsDetails[i].cgType==4&&formData.value.fourFuKuan==null){
    message.error('付款类型跟订单不一致,不允许添加')
    return false
  }
  if (formData.value.orderYsDetails[i].cgType==5&&formData.value.fiveFuKuan==null){
    message.error('付款类型跟订单不一致,不允许添加')
    return false
  }
  if (formData.value.orderYsDetails[i].cgType==6&&formData.value.sixFuKuan==null){
    message.error('付款类型跟订单不一致,不允许添加')
    return false
  }
  }
    if (formData.value.cgYishou>=formData.value.cgYs){
      message.error('已收金额大于应收金额,请确认')
      return false
    }
  if (formData.value.cgYishou!=''&&formData.value.cgYishou!=undefined&&formData.value.cgYishou!=null){
    if (formData.value.cgYishou<formData.value.cgYs&&formData.value.cgTypee==1){
      await message.confirm("已收金额小于应收金额,回款未全部完成,请确认")
    }else if (formData.value.cgYishou>=formData.value.cgYs&&formData.value.cgTypee==2){
      await  message.confirm("已收金额大于等于应收金额,回款已完成,请确认")
    }else if (formData.value.cgTypee==3){
      await  message.confirm("已收金额不为0,不能选择未付款,请确认")
    }
  }else {
    if (formData.value.cgTypee==2||formData.value.cgTypee==1){
      await message.confirm("未输入已收金额,回款未完成,请确认")
    }
  }
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as OrderYsApi.OrderYsVO

    if (formType.value === 'create') {
      await OrderYsApi.createOrderYs(data)
      message.success(t('common.createSuccess'))
    } else {
      await OrderYsApi.updateOrderYs(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}
/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    code: undefined,
    projectName: undefined,
    cgTime: undefined,
    cgKhname: undefined,
    cgYs: undefined,
    cgYishou: undefined,
    cgTypee: undefined,
    rem: undefined,
  }
  formRef.value?.resetFields()
}
</script>
