<template>
  <el-row :gutter="20">
    <el-col :span="16">
      <ContentWrap title="申请信息">
        <el-form
          ref="formRef"
          v-loading="formLoading"
          :model="formData"
          :rules="formRules"
          label-width="100px"
        >
          <!-- 两列布局 -->
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="凭证号" prop="no">
                <el-input
                  v-model="formData.no"
                  placeholder="请输入凭证号（留空将自动生成）"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="凭证日期" prop="voucherTime">
                <el-date-picker
                  v-model="formData.voucherTime"
                  clearable
                  placeholder="请选择凭证日期"
                  type="date"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="付款时间" prop="paymentDate">
                <el-date-picker
                  v-model="formData.paymentDate"
                  clearable
                  placeholder="请选择付款时间"
                  type="date"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="单据类型" prop="billType">
                <el-select
                  v-model="formData.billType"
                  clearable
                  placeholder="请选择单据类型"
                  style="width: 100%"
                >
                  <el-option
                    v-for="dict in getIntDictOptions(DICT_TYPE.ERP_FINANCE_RECEIPT_TYPE)"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="凭证类型" prop="type">
                <el-select
                  v-model="formData.type"
                  clearable
                  placeholder="请选择凭证类型"
                  style="width: 100%"
                >
                  <el-option
                    v-for="dict in getIntDictOptions(DICT_TYPE.ERP_FINANCE_VOUCHER_TYPE)"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="收款单位" prop="payeeName">
                <el-input v-model="formData.payeeName" placeholder="请输入收款单位" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="项目名称" prop="projectName">
                <el-input v-model="formData.projectName" placeholder="请输入项目名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="开户银行" prop="bankName">
                <el-input v-model="formData.bankName" placeholder="请输入开户银行" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="开户账号" prop="bankAccount">
                <el-input v-model="formData.bankAccount" placeholder="请输入开户账号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="合同号" prop="contractNo">
                <el-input v-model="formData.contractNo" placeholder="请输入合同号" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="合同总金额" prop="contractAmount">
                <el-input-number
                  v-model="formData.contractAmount"
                  :min="0"
                  :precision="4"
                  :controls="false"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="税号" prop="taxNo">
                <el-input v-model="formData.taxNo" placeholder="请输入税号" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="累计已付金额" prop="paidAmount">
                <el-input-number
                  v-model="formData.paidAmount"
                  :min="0"
                  :precision="4"
                  :controls="false"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="合同附件" prop="contractFile">
                <el-upload
                  action="#"
                  :http-request="uploadContractFile"
                  :limit="1"
                  :file-list="contractFileList"
                >
                  <el-button type="primary">上传合同附件</el-button>
                  <template #tip>
                    <div class="el-upload__tip">请上传合同相关文件</div>
                  </template>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="发票附件" prop="invoiceFile">
                <el-upload
                  action="#"
                  :http-request="uploadInvoiceFile"
                  :limit="5"
                  :file-list="invoiceFileList"
                  multiple
                >
                  <el-button type="primary">上传发票附件</el-button>
                  <template #tip>
                    <div class="el-upload__tip">可上传多个发票文件</div>
                  </template>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="备注" prop="remark">
            <el-input v-model="formData.remark" placeholder="请输入备注" type="textarea" />
          </el-form-item>

          <!-- 凭证明细 -->
          <el-form-item label="凭证明细" prop="items">
            <el-table :data="formData.items" border>
              <el-table-column label="序号" type="index" width="50" align="center" />
              <el-table-column label="摘要" prop="summary" min-width="180">
                <template #default="scope">
                  <el-input v-model="scope.row.summary" placeholder="请输入摘要" />
                </template>
              </el-table-column>
              <el-table-column label="会计科目" prop="accountId" min-width="180">
                <template #default="scope">
                  <el-select
                    v-model="scope.row.accountId"
                    placeholder="请选择会计科目"
                    style="width: 100%"
                    filterable
                  >
                    <el-option
                      v-for="item in accountOptions"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    >
                      <span>{{ item.name }}</span>
                      <span class="subject-direction">{{ getSubjectDirection(item.id) }}</span>
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="借方金额" prop="debitAmount" align="right" min-width="120">
                <template #default="scope">
                  <el-input-number
                    v-model="scope.row.debitAmount"
                    :min="0"
                    :precision="4"
                    :disabled="
                      scope.row.creditAmount > 0 || shouldDisableDebit(scope.row.accountId)
                    "
                    @change="calculateTotal"
                    style="width: 100%"
                  />
                </template>
              </el-table-column>
              <el-table-column label="贷方金额" prop="creditAmount" align="right" min-width="120">
                <template #default="scope">
                  <el-input-number
                    v-model="scope.row.creditAmount"
                    :min="0"
                    :precision="4"
                    :disabled="
                      scope.row.debitAmount > 0 || shouldDisableCredit(scope.row.accountId)
                    "
                    @change="calculateTotal"
                    style="width: 100%"
                  />
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="80">
                <template #default="scope">
                  <el-button
                    type="danger"
                    icon="Delete"
                    size="small"
                    @click="handleDeleteItem(scope.$index)"
                  />
                </template>
              </el-table-column>
            </el-table>

            <!-- 添加明细按钮 -->
            <div class="mt-2">
              <el-button type="primary" @click="handleAddItem">
                <Icon class="mr-5px" icon="ep:plus" />
                添加明细
              </el-button>
            </div>

            <!-- 合计金额 -->
            <div class="text-right mt-2">
              <span class="font-bold">合计金额: {{ totalAmount }}</span>
            </div>
          </el-form-item>

          <el-form-item>
            <el-button :disabled="formLoading" type="primary" @click="submitForm">
              确 定
            </el-button>
          </el-form-item>
        </el-form>
      </ContentWrap>
    </el-col>

    <!-- 审批相关：流程信息 -->
    <el-col :span="8">
      <ContentWrap title="审批流程" :bodyStyle="{ padding: '0 20px 0' }">
        <ProcessInstanceTimeline
          ref="timelineRef"
          :activity-nodes="activityNodes"
          :show-status-icon="false"
          @select-user-confirm="selectUserConfirm"
        />
      </ContentWrap>
    </el-col>
  </el-row>
</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import * as VoucherApi from '@/api/erp/finance/voucher/voucher'
import { useTagsViewStore } from '@/store/modules/tagsView'
import * as FileApi from '@/api/infra/file'
import { SubjectApi } from '@/api/erp/finance/subject'

// 审批相关：import
import * as DefinitionApi from '@/api/bpm/definition'
import ProcessInstanceTimeline from '@/views/bpm/processInstance/detail/ProcessInstanceTimeline.vue'
import * as ProcessInstanceApi from '@/api/bpm/processInstance'
import { CandidateStrategy, NodeId } from '@/components/SimpleProcessDesignerV2/src/consts'
import { ApprovalNodeInfo } from '@/api/bpm/processInstance'

defineOptions({ name: 'ErpFinanceVoucherCreate' })

const message = useMessage() // 消息弹窗
const { delView } = useTagsViewStore() // 视图操作
const { push, currentRoute } = useRouter() // 路由

const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const accountOptions = ref<{ id: number; name: string; direction?: number }[]>([]) // 会计科目列表
const totalAmount = ref(0) // 合计金额
const contractFileList = ref<any[]>([]) // 合同附件列表
const invoiceFileList = ref<any[]>([]) // 发票附件列表
const subjectDirections = ref<Record<number, number>>({}) // 科目余额方向映射

const formData = ref({
  type: undefined as number | undefined,
  billType: undefined as number | undefined,
  voucherTime: undefined as string | undefined,
  paymentDate: undefined as string | undefined,
  no: '', // 凭证号
  payeeName: '', // 收款单位
  projectName: '', // 项目名称
  bankName: '', // 开户银行
  bankAccount: '', // 开户账号
  contractNo: '', // 合同号
  contractAmount: 0, // 合同总金额
  taxNo: '', // 税号
  paidAmount: 0, // 累计已付金额
  contractFile: '', // 合同附件
  invoiceFile: '', // 发票附件
  remark: '',
  items: [] as VoucherApi.VoucherItemVO[]
})
const formRules = reactive({
  // type: [{ required: true, message: '凭证类型不能为空', trigger: 'blur' }],
  voucherTime: [{ required: true, message: '凭证日期不能为空', trigger: 'change' }],
  paymentDate: [{ required: true, message: '付款时间不能为空', trigger: 'change' }],
  billType: [{ required: true, message: '单据类型不能为空', trigger: 'change' }],
  payeeName: [{ required: true, message: '收款单位不能为空', trigger: 'blur' }],
  projectName: [{ required: true, message: '项目名称不能为空', trigger: 'blur' }],
  bankName: [{ required: true, message: '开户银行不能为空', trigger: 'blur' }],
  bankAccount: [{ required: true, message: '开户账号不能为空', trigger: 'blur' }],
  contractNo: [{ required: true, message: '合同号不能为空', trigger: 'blur' }],
  items: [{ required: true, message: '至少添加一条明细', trigger: 'change' }]
})
const formRef = ref() // 表单 Ref

// 审批相关：变量
// const processDefineKey = 'erp_finance_voucher' // 流程定义 Key
const processDefineKey = 'erp_finance_voucher' // 流程定义 Key，需要与SQL中配置的一致
const startUserSelectTasks = ref<any[]>([]) // 发起人需要选择审批人的用户任务列表
const startUserSelectAssignees = ref<Record<string, number[]>>({}) // 发起人选择审批人的数据
const tempStartUserSelectAssignees = ref<Record<string, number[]>>({}) // 历史发起人选择审批人的数据，用于每次表单变更时，临时保存
const activityNodes = ref<ProcessInstanceApi.ApprovalNodeInfo[]>([]) // 审批节点信息
const processDefinitionId = ref('')

/** 提交表单 */
const submitForm = async () => {
  // 1.1 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 1.2 审批相关：校验指定审批人
  if (startUserSelectTasks.value?.length > 0) {
    for (const userTask of startUserSelectTasks.value) {
      if (
        Array.isArray(startUserSelectAssignees.value[userTask.id]) &&
        startUserSelectAssignees.value[userTask.id].length === 0
      ) {
        return message.warning(`请选择${userTask.name}的审批人`)
      }
    }
  }

  // 2. 提交请求
  formLoading.value = true
  try {
    const data = { ...formData.value } as unknown as VoucherApi.VoucherVO
    // 审批相关：设置指定审批人
    if (startUserSelectTasks.value?.length > 0) {
      data.startUserSelectAssignees = startUserSelectAssignees.value
    }
    await VoucherApi.createVoucher(data)
    message.success('发起成功')
    // 关闭当前 Tab
    delView(unref(currentRoute))
    await push({ name: 'ErpFinanceVoucher' })
  } finally {
    formLoading.value = false
  }
}

/** 上传合同附件 */
const uploadContractFile = async (options: any) => {
  const { file, onSuccess, onError } = options
  try {
    const response = await FileApi.updateFile({ file })
    if (response.code === 0) {
      formData.value.contractFile = response.data
      contractFileList.value = [{ name: file.name, url: response.data }]
      onSuccess()
    } else {
      onError(new Error(response.msg || '上传失败'))
    }
  } catch (error) {
    console.error('上传合同附件失败', error)
    onError(error)
  }
}

/** 上传发票附件 */
const uploadInvoiceFile = async (options: any) => {
  const { file, onSuccess, onError } = options
  try {
    const response = await FileApi.updateFile({ file })
    if (response.code === 0) {
      if (formData.value.invoiceFile) {
        formData.value.invoiceFile += ',' + response.data
      } else {
        formData.value.invoiceFile = response.data
      }
      invoiceFileList.value.push({ name: file.name, url: response.data })
      onSuccess()
    } else {
      onError(new Error(response.msg || '上传失败'))
    }
  } catch (error) {
    console.error('上传发票附件失败', error)
    onError(error)
  }
}

/** 审批相关：获取审批详情 */
const getApprovalDetail = async () => {
  try {
    // 如果processDefinitionId为空，则不调用接口
    if (!processDefinitionId.value) {
      return
    }

    const data = await ProcessInstanceApi.getApprovalDetail({
      processDefinitionId: processDefinitionId.value,
      activityId: NodeId.START_USER_NODE_ID,
      processVariablesStr: JSON.stringify({ totalAmount: totalAmount.value }) // 解决 GET 无法传递对象的问题，后端 String 再转 JSON
    })

    if (!data) {
      message.error('查询不到审批详情信息！')
      return
    }
    // 获取审批节点，显示 Timeline 的数据
    activityNodes.value = data.activityNodes

    // 获取发起人自选的任务
    startUserSelectTasks.value = data.activityNodes?.filter(
      (node: ApprovalNodeInfo) => CandidateStrategy.START_USER_SELECT === node.candidateStrategy
    )
    // 恢复之前的选择审批人
    if (startUserSelectTasks.value?.length > 0) {
      for (const node of startUserSelectTasks.value) {
        if (
          tempStartUserSelectAssignees.value[node.id] &&
          tempStartUserSelectAssignees.value[node.id].length > 0
        ) {
          startUserSelectAssignees.value[node.id] = tempStartUserSelectAssignees.value[node.id]
        } else {
          startUserSelectAssignees.value[node.id] = []
        }
      }
    }
  } finally {
  }
}

/** 审批相关：选择发起人 */
const selectUserConfirm = (id: string, userList: any[]) => {
  startUserSelectAssignees.value[id] = userList?.map((item: any) => item.id)
}

/** 添加明细 */
const handleAddItem = () => {
  formData.value.items.push({
    accountId: 0, // 初始化为0而不是undefined
    summary: '',
    debitAmount: 0,
    creditAmount: 0
  })
}

/** 删除明细 */
const handleDeleteItem = (index: number) => {
  formData.value.items.splice(index, 1)
  calculateTotal()
}

/** 计算合计金额 */
const calculateTotal = () => {
  let total = 0
  for (const item of formData.value.items) {
    total += Number(item.debitAmount || 0)
  }
  totalAmount.value = total
}

/** 获取科目余额方向 */
const getSubjectDirection = (accountId: number) => {
  if (!accountId) return ''
  const direction = subjectDirections.value[accountId]
  return direction === 1 ? '(借)' : direction === 2 ? '(贷)' : ''
}

/** 是否禁用借方输入 */
const shouldDisableDebit = (accountId: number) => {
  if (!accountId) return false
  const direction = subjectDirections.value[accountId]
  return direction === 2 // 贷方科目禁用借方输入
}

/** 是否禁用贷方输入 */
const shouldDisableCredit = (accountId: number) => {
  if (!accountId) return false
  const direction = subjectDirections.value[accountId]
  return direction === 1 // 借方科目禁用贷方输入
}

/** 加载会计科目选项 */
const loadAccountOptions = async () => {
  try {
    // 从后端获取会计科目列表
    const subjects = await SubjectApi.getSubjectSimpleList()
    accountOptions.value = subjects.map((subject) => ({
      id: subject.id,
      name: `${subject.code} - ${subject.name}`,
      direction: subject.direction
    }))

    // 构建科目余额方向映射
    subjects.forEach((subject) => {
      subjectDirections.value[subject.id] = subject.direction
    })
  } catch (error) {
    console.error('获取会计科目列表失败', error)
    message.error('获取会计科目列表失败')
  }
}

/** 初始化 */
onMounted(async () => {
  // 加载会计科目
  await loadAccountOptions()
  // 添加一条空的明细
  handleAddItem()

  // 获取流程定义
  try {
    const processDefinitionDetail = await DefinitionApi.getProcessDefinition(
      undefined,
      processDefineKey
    )

    if (!processDefinitionDetail) {
      message.error('财务凭证的流程模型未配置，请检查！')
      return
    }
    processDefinitionId.value = processDefinitionDetail.id
    startUserSelectTasks.value = processDefinitionDetail.startUserSelectTasks

    // 审批相关：加载最新的审批详情，主要用于节点预测
    // 确保已经获取到processDefinitionId后再调用getApprovalDetail
    if (processDefinitionId.value) {
      await getApprovalDetail()
    }
  } catch (error) {
    console.error('获取流程定义失败', error)
    message.error('获取流程定义失败，请检查流程配置！')
  }
})

/** 审批相关：预测流程节点会因为输入的参数值而产生新的预测结果值，所以需重新预测一次 */
watch(
  formData.value,
  (newValue, oldValue) => {
    if (!oldValue) {
      return
    }
    // 确保已经获取到processDefinitionId后再调用getApprovalDetail
    if (newValue && Object.keys(newValue).length > 0 && processDefinitionId.value) {
      // 记录之前的节点审批人
      tempStartUserSelectAssignees.value = startUserSelectAssignees.value
      startUserSelectAssignees.value = {}
      // 加载最新的审批详情,主要用于节点预测
      getApprovalDetail()
    }
  },
  {
    immediate: false // 修改为false，避免在初始化时就触发
  }
)
</script>

<style scoped>
.mt-2 {
  margin-top: 8px;
}
.text-right {
  text-align: right;
}
.font-bold {
  font-weight: bold;
}
.subject-direction {
  float: right;
  color: #909399;
  font-size: 13px;
}
</style>
