<template>
  <div class="layout-padding-auto layout-padding-view bg-info" v-show="visible" v-loading="loading" :key="componentKey">
    <!-- 按钮区域 -->
    <div class="menu_boxs">
      <div class="avue-crud__menu">
        <div class="avue-crud__left">
          <el-button v-if="showOperateType !== 'view'" :disabled="!saveBtn" icon="DocumentChecked" type="primary" @click="saveClick(true)">
            {{ t('common.saveBtn') }}
          </el-button>
          <el-button icon="Close" @click="gobackClick" v-if="!route.query.taskId">
            {{ t('common.gobackBtn') }}
          </el-button>
          <el-button v-if="isSubmitShow" icon="Select" type="primary" @click="submitHandle(true)">
            {{ t('common.submit') }}
          </el-button>
          <process v-if="isProcessState" :operateType="showOperateType" :beforeFlow="beforeFlow" :currentRow="dataForm"
            @workflowPopClose="workflowPopClose" @afterFlowHandle="afterFlowHandle" />
          <el-button type="primary" @click="handleToggleCollapseExpand()">
            {{ t('common.retract_expand') }}
          </el-button>
          <el-button type="primary" circle icon="Share" style="position: absolute; right: 20px" @click="gobackClick"></el-button>
        </div>
      </div>
    </div>

    <!-- 表单区域 -->
    <el-row class="rounded-1 form_h">
      <el-collapse v-model="activeNames">
        <el-form ref="dataFormRef" :model="dataForm" :rules="dataMasterRules" formDialogRef :label-width="cfg.labelWidth" :disabled="FormDisabled">
          <!-- 基本信息 -->
          <div class="basic">
            <basic-container>
              <el-collapse-item :title="t(`column.${processDefKey}.master.masterCollapseTitle`)" name="0">
                <!-- 第1行：input(disabled) + date-picker + input(带搜索弹窗) + input(带搜索弹窗+禁用条件) -->
                <el-row>
                  <el-col :span="6">
                    <el-form-item :label="t(`column.${processDefKey}.master.billCode`)" prop="billCode">
                      <el-input v-model="dataForm.billCode" placeholder="" disabled />
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item :label="t(`column.${processDefKey}.master.billDate`)" prop="billDate">
                      <el-date-picker v-model="dataForm.billDate" type="dateTime"
                        :placeholder="`${t('message.pleaseSelect')}${t(`column.${processDefKey}.master.billDate`)}`"
                        value-format="YYYY-MM-DD" format="YYYY-MM-DD" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item :label="t(`column.${processDefKey}.master.projectName`)" prop="projectName">
                      <el-input disabled v-model="dataForm.projectName" maxlength="32"
                        :placeholder="`${t('message.pleaseSelect')}${t(`column.${processDefKey}.master.projectName`)}`">
                        <template #append>
                          <el-button @click="projectMasterSelectProjectClick()" icon="Search"></el-button>
                        </template>
                      </el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item :label="t(`column.${processDefKey}.master.owner`)" prop="owner">
                      <el-input disabled v-model="dataForm.owner" maxlength="32"
                        :placeholder="`${t('message.pleaseSelect')}${t(`column.${processDefKey}.master.owner`)}`">
                        <template #append>
                          <el-button :disabled="isOwnerDisabled" @click="ownerInfoRegSelectOwnerClick()" icon="Search"></el-button>
                        </template>
                      </el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <!-- 第2行：select + radio-group + radio-group + number(microme-operator) -->
                <el-row>
                  <el-col :span="6">
                    <el-form-item :label="t(`column.${processDefKey}.master.debtProtocolType`)" prop="debtProtocolType">
                      <el-select filterable v-model="dataForm.debtProtocolType" clearable
                        :placeholder="`${t('message.pleaseSelect')}${t(`column.${processDefKey}.master.debtProtocolType`)}`">
                        <el-option v-for="item in debtProtocolTypeOptions" :key="item.id" :label="item.label" :value="item.value"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item :label="t(`column.${processDefKey}.master.contractDebtTermsFlag`)" prop="contractDebtTermsFlag">
                      <el-radio-group v-model="dataForm.contractDebtTermsFlag">
                        <el-radio :key="index" :label="item.value" v-for="(item, index) in contractDebtTermsFlagOptions">
                          {{ item.label }}
                        </el-radio>
                      </el-radio-group>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item :label="t(`column.${processDefKey}.master.determinationBasisOffsetValue`)" prop="determinationBasisOffsetValue">
                      <el-radio-group v-model="dataForm.determinationBasisOffsetValue">
                        <el-radio :key="index" :label="item.value" v-for="(item, index) in determinationBasisOffsetValueOptions">
                          {{ item.label }}
                        </el-radio>
                      </el-radio-group>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item :label="t(`column.${processDefKey}.master.debtAmount`)" prop="debtAmount">
                      <microme-operator :disabled="true" :value="dataForm.debtAmount" :placeholder="``"
                        @change="($event) => (dataForm.debtAmount = $event)"></microme-operator>
                    </el-form-item>
                  </el-col>
                </el-row>
                <!-- 第3行：textarea (span=24全宽) -->
                <el-row>
                  <el-col :span="24">
                    <el-form-item :label="t(`column.${processDefKey}.master.contractDebtContent`)" prop="contractDebtContent">
                      <el-input type="textarea" rows="5" maxlength="500" show-word-limit v-model="dataForm.contractDebtContent"
                        :placeholder="`${t('message.pleaseEnter')}${t(`column.${processDefKey}.master.contractDebtContent`)}`"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item :label="t(`column.${processDefKey}.master.debtBusinessReason`)" prop="debtBusinessReason">
                      <el-input type="textarea" rows="5" maxlength="500" show-word-limit v-model="dataForm.debtBusinessReason"
                        :placeholder="`${t('message.pleaseEnter')}${t(`column.${processDefKey}.master.debtBusinessReason`)}`"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <!-- 附件字段行：upload-file (span=24全宽)，多个附件字段结构相同 -->
                <el-row>
                  <el-col :span="24">
                    <el-form-item :label="t(`column.${processDefKey}.master.attachmentDebtsAssetsBusinessApply`)" prop="attachmentDebtsAssetsBusinessApply">
                      <upload-file v-model:modelValue="dataForm.attachmentDebtsAssetsBusinessApply"> </upload-file>
                    </el-form-item>
                  </el-col>
                </el-row>
                <!-- 其他附件字段同上结构：attachmentOwnerSubcontractDistributionSettlement, attachmentAssetsValuationStatement, attachmentMarketValueCertificate, attachmentProposedContract -->
                <el-row>
                  <el-col :span="24">
                    <el-form-item :label="t(`column.${processDefKey}.master.attachmentProposedContract`)" prop="attachmentProposedContract">
                      <upload-file v-model:modelValue="dataForm.attachmentProposedContract"> </upload-file>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-collapse-item>
            </basic-container>
          </div>
          <!-- 子表：抵入资产信息 -->
          <div class="basic">
            <basic-container>
              <el-collapse-item :title="t(`column.${processDefKey}.master.detailCollapseTitle`)" name="1">
                <div class="btn">
                  <el-button :disabled="isAddDetailDisabled" icon="Plus" type="primary" @click="addDetailClick()">
                    {{ t(`column.${processDefKey}.master.addDetail`) }}
                  </el-button>
                  <el-button :disabled="isDelDetailDisabled" type="primary" icon="el-icon-delete" @click="deleteDetailClick()">
                    {{ t('common.delBtn') }}
                  </el-button>
                </div>
                <el-table :data="dataForm.detail"
                  :row-class-name="({ row }) => (detailSelectRows.find((item) => item.id === row.id) ? 'selectRowColor' : '')"
                  ref="detailTable" @selection-change="detailSelectChangeHandle" @current-change="detailCurrentRowChangeHandle">
                  <el-table-column type="selection" width="40" align="center"> </el-table-column>
                  <el-table-column type="index" fixed class-name="no-dragging" :label="t('common.serial')" width="80" align="center" />
                  <!-- 子表列：input类型 -->
                  <el-table-column prop="assetName" show-overflow-tooltip :label="t(`column.${processDefKey}.detail.assetName`)"
                    header-align="center" :min-width="detailColumns.filter((c) => c.key === 'assetName')[0]?.width" align="center">
                    <template v-slot="{ $index, row }">
                      <el-form-item label-width="0" :rules="dataDetailRules.assetName" :prop="`detail.${$index}.assetName`">
                        <el-input style="width: 99%" v-model="row.assetName" maxlength="100"
                          :placeholder="`${t('message.pleaseEnter')}${t(`column.${processDefKey}.detail.assetName`)}`" />
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <!-- 子表列：select类型 -->
                  <el-table-column prop="assetClass" show-overflow-tooltip :label="t(`column.${processDefKey}.detail.assetClass`)"
                    header-align="center" :min-width="detailColumns.filter((c) => c.key === 'assetClass')[0]?.width" align="center">
                    <template v-slot="{ $index, row }">
                      <el-form-item label-width="0" :rules="dataDetailRules.assetClass" :prop="`detail.${$index}.assetClass`">
                        <el-select filterable v-model="row.assetClass" clearable
                          :placeholder="`${t('message.pleaseSelect')}${t(`column.${processDefKey}.detail.assetClass`)}`" style="width: 99%">
                          <el-option v-for="item in assetClassOptions" :key="item.id" :label="item.label" :value="item.value"></el-option>
                        </el-select>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <!-- 子表列：microme-operator数字类型 -->
                  <el-table-column prop="valuationValue" show-overflow-tooltip :label="t(`column.${processDefKey}.detail.valuationValue`)"
                    header-align="center" :min-width="detailColumns.filter((c) => c.key === 'valuationValue')[0]?.width" align="center">
                    <template v-slot="{ $index, row }">
                      <el-form-item label-width="0" :rules="dataDetailRules.valuationValue" :prop="`detail.${$index}.valuationValue`">
                        <microme-operator style="width: 99%" @change="($event) => (row.valuationValue = $event)" :value="row.valuationValue"
                          :placeholder="`${t('message.pleaseEnter')}${t(`column.${processDefKey}.detail.valuationValue`)}`"></microme-operator>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <!-- 子表列：microme-operator数字类型(disabled) -->
                  <el-table-column prop="proposedOffsetValue" show-overflow-tooltip :label="t(`column.${processDefKey}.detail.proposedOffsetValue`)"
                    header-align="center" :min-width="detailColumns.filter((c) => c.key === 'proposedOffsetValue')[0]?.width" align="center">
                    <template v-slot="{ $index, row }">
                      <el-form-item label-width="0" :rules="dataDetailRules.proposedOffsetValue" :prop="`detail.${$index}.proposedOffsetValue`">
                        <microme-operator disabled style="width: 99%" @change="($event) => (row.proposedOffsetValue = $event)"
                          :value="row.proposedOffsetValue" :placeholder="` `"></microme-operator>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <!-- 子表列：input备注 -->
                  <el-table-column prop="remark" show-overflow-tooltip :label="t(`column.${processDefKey}.detail.remark`)"
                    header-align="center" :min-width="detailColumns.filter((c) => c.key === 'remark')[0]?.width" align="center">
                    <template v-slot="{ $index, row }">
                      <el-form-item label-width="0" :rules="dataDetailRules.remark" :prop="`detail.${$index}.remark`">
                        <el-input style="width: 99%" v-model="row.remark" maxlength="200"
                          :placeholder="`${t('message.pleaseEnter')}${t(`column.${processDefKey}.detail.remark`)}`" />
                      </el-form-item>
                    </template>
                  </el-table-column>
                </el-table>
              </el-collapse-item>
            </basic-container>
          </div>
          <!-- 填报信息 -->
          <div class="basic">
            <basic-container>
              <el-collapse-item :title="t(`column.${processDefKey}.master.masterCreateCollapseTitle`)" name="3">
                <el-row>
                  <el-col :span="6">
                    <el-form-item :label="t(`column.${processDefKey}.master.createUser`)" prop="createUser">
                      <el-input v-model="dataForm.createUser" placeholder="" disabled />
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item :label="t(`column.${processDefKey}.master.createTime`)" prop="createTime">
                      <el-input v-model="dataForm.createTime" placeholder="" disabled />
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item :label="t(`column.${processDefKey}.master.finishedTime`)" prop="finishedTime">
                      <el-input v-model="dataForm.finishedTime" placeholder="" disabled />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-collapse-item>
            </basic-container>
          </div>
        </el-form>
      </el-collapse>
    </el-row>
  </div>
  <!-- 弹窗组件 -->
  <select-project ref="ProjectMasterSelectProject" :title="t('message.ProjectSelectProjectDialog')" @okHandle="projectMasterSelectProjectOkHandle"></select-project>
  <select-owner ref="selectOwnerRef" :title="t('message.pleaseSelect') + t(`column.${processDefKey}.master.owner`)" @okHandle="selectOwnerOkHandle"></select-owner>
</template>
<script setup lang="ts" name="DebtProjectAssetsOffsetDialog">
import { useMessage, useMessageBox } from '/@/hooks/message'
import { fetchList, getObj, addObj, putObj, getOwner, getProjectVal } from '/@/api/financialcapital/DebtProjectAssetsOffset'
import { useI18n } from 'vue-i18n'
import { formValidate } from '/@/utils/verify'
import { unique } from '/@/utils/common'
import moment from 'moment'
import { dataDetailEntity } from './options'
import { useDynamicsShowColumn } from '/@/hooks/table'
import { getCurrPsmInfo, getMainPosPsmInfo, getMenuObjByMenuPath, getProcessFunction, getIsProcessByBusinessId, getProject } from '/@/util/util'
import { formatMoney } from '/@/utils/formatMoney'
import { inputNumber } from '/@/utils/inputNumber'
import { bill_state, debt_protocol_type, common_status, determination_basis_offset_value, debt_assets_type } from '/@/enums/dict'

const componentKey = ref(0)
const emit = defineEmits(['goback', 'refresh'])
const { t } = useI18n()
const ProjectMasterSelectProject = ref()
const selectOwnerRef = ref()
const dataFormRef = ref()
const saveBtn = ref(false)
const oldValue = ref<any>()
const visible = ref(false)
const loading = ref(false)
const showOperateType = ref('view')
const route = useRoute()
const processDefKey = getMenuObjByMenuPath(route.path).modelId
const isProcessFunction = ref(false)
const activeFlag = ref(true)
const activeNames = ref(['0', '1', '2', '3'])
const collapseItemName: Array<string> = ['0', '1', '2', '3']
const detailCurrentRow = reactive({})
const detailSelectRows = ref<any>([])
const detailTable = ref()
const detailColumns = ref([] as any[])
const detailDProjectCurrentRow = reactive({})
const detailDProjectSelectRows = ref<any>([])
const SelectProjectDetailDProject = ref()
const SelectContractDetailDProject = ref()
const cfg = reactive({ gutter: 16, span: 12, labelWidth: '170px' })
const startNodeKey = ref('userTask1')

const dataForm = reactive({
  billCode: null, billState: null, billStateId: '0',
  billDate: moment(new Date()).format('YYYY-MM-DD'),
  projectCode: null, projectId: null, projectName: null,
  ownerId: null, ownerCreditCode: null, owner: null,
  debtProtocolType: null, contractDebtTermsFlag: null,
  determinationBasisOffsetValue: null, debtAmount: null,
  contractDebtContent: null, debtBusinessReason: null,
  amountDebtRepayment: null,
  attachmentDebtsAssetsBusinessApply: null,
  attachmentOwnerSubcontractDistributionSettlement: null,
  attachmentAssetsValuationStatement: null,
  attachmentMarketValueCertificate: null,
  attachmentProposedContract: null,
  amountContract: null, amountConfirmed: null,
  amountContractReceivable: null, amountReceived: null,
  amountReceivableBalanceAccounts: null,
  amountOverdueAccountsReceivable: null,
  createUserId: getCurrPsmInfo().userId, createUser: getCurrPsmInfo().user,
  createPosId: null, createPos: null,
  createDptId: null, createDpt: null,
  createOgnId: null, createOgn: null,
  createPsmFullId: null, createPsmFullName: null,
  updatePsmFullId: null, updatePsmFullName: null,
  createTime: null, updateTime: null,
  tenantId: null, id: null, version: '',
  remark: null, finishedTime: null,
  businessType: '1', debtAssetsType: null,
  detail: [] as any,
  isProcessData: '',
})
const initForm = Object.assign({}, dataForm)

// 通用必填验证规则生成
const requiredRule = (entity: string, field: string) => [{
  required: true,
  message: t(`column.${processDefKey}.${entity}.${field}`) + t('message.not_empty'),
  trigger: ['blur', 'change']
}]

const dataMasterRules = ref({
  billDate: requiredRule('master', 'billDate'),
  projectName: requiredRule('master', 'projectName'),
  owner: requiredRule('master', 'owner'),
  debtProtocolType: requiredRule('master', 'debtProtocolType'),
  contractDebtTermsFlag: requiredRule('master', 'contractDebtTermsFlag'),
  determinationBasisOffsetValue: requiredRule('master', 'determinationBasisOffsetValue'),
  contractDebtContent: requiredRule('master', 'contractDebtContent'),
  debtBusinessReason: requiredRule('master', 'debtBusinessReason')
})

const dataDetailRules = ref({
  assetName: requiredRule('detail', 'assetName'),
  assetClass: requiredRule('detail', 'assetClass'),
  detailInfo: requiredRule('detail', 'detailInfo'),
  transferFlag: requiredRule('detail', 'transferFlag'),
  measureUnit: requiredRule('detail', 'measureUnit'),
  number: requiredRule('detail', 'number'),
  unitPrice: requiredRule('detail', 'unitPrice'),
  valuationValue: requiredRule('detail', 'valuationValue'),
  proposedOffsetValue: requiredRule('detail', 'proposedOffsetValue')
})

// 字典选项
let billStateIdOptions: any = reactive([])
let debtProtocolTypeOptions: any = reactive([])
let contractDebtTermsFlagOptions: any = reactive([])
let determinationBasisOffsetValueOptions: any = reactive([])
let assetClassOptions: any = reactive([])
let transferFlagOptions: any = reactive([])

useDynamicsShowColumn(detailColumns, dataDetailEntity)

// 金额字段集合（用于统一格式化）
const moneyFields = ['amountContract', 'amountConfirmed', 'amountPayable', 'amountDiscount', 'amountPaid', 'amountReceivableBalanceAccounts', 'amountDebtRepayment']
const format = (row, column, cellValue, index) => {
  if (moneyFields.includes(column.property)) {
    return cellValue ? formatMoney(inputNumber(String(cellValue))) + t('common.yuan') : '0' + t('common.yuan')
  }
  return cellValue
}

// 子表：新增行
const addDetailClick = () => {
  dataForm.detail.push({
    assetName: '', assetClass: '', detailInfo: '', transferFlag: '',
    measureUnit: '', number: '', unitPrice: '', valuationValue: '',
    proposedOffsetValue: '', remark: '', detailProject: [],
    id: -new Date().getTime()
  })
  nextTick(() => {
    detailTable.value.setCurrentRow(dataForm.detail[0], true)
  })
  // 加载子表关联的项目信息
  if (dataForm.detail[0].detailProject.length) {
    dataForm.detailDProject = dataForm.detail[0].detailProject
  } else {
    getProjectVal({ current: 1, size: -1, projectId: dataForm.projectId, creditCode: dataForm.ownerCreditCode }).then((response) => {
      dataForm.detailDProject = response.data
      dataForm.detailDProject.map((item) => {
        item.amountDebtRepayment = ''
        item.amountReceivableBalanceAccounts = Number(item.amountPayable) - Number(item.amountPaid)
      })
      dataForm.detail[0].detailProject = dataForm.detailDProject
    })
  }
}

// 子表：删除选中行
const deleteDetailClick = () => {
  dataForm.detail = dataForm.detail.filter((item: any) => !detailSelectRows.value.some((ele: any) => ele.id === item.id))
  if (dataForm.detail.length > 0) {
    nextTick(() => { detailTable.value.toggleRowSelection(dataForm.detail[0], true) })
    dataForm.detailDProject = []
    dataForm.debtAmount = 0
    dataForm.detail.map((item) => { dataForm.debtAmount += Number(item.proposedOffsetValue) })
    if (dataForm.detail[0]) {
      dataForm.detailDProject = dataForm.detail[0].detailProject
    } else {
      dataForm.detailDProject = []
    }
  } else {
    dataForm.debtAmount = null
    dataForm.detailDProject = []
    Object.assign(detailCurrentRow, {})
  }
}

// 子表：选择变化
const detailSelectChangeHandle = (rows: any) => {
  Object.assign(detailCurrentRow, rows[0])
  detailSelectRows.value = rows
}

// 子表：当前行变化（单击行时加载关联的项目信息）
const detailCurrentRowChangeHandle = (row) => {
  detailSelectRows.value = []
  if (row) {
    Object.assign(detailCurrentRow, row)
    detailTable.value.clearSelection()
    detailSelectRows.value.push(row)
    detailTable.value.toggleRowSelection(row, true)
    nextTick(() => {
      if (detailSelectRows.value[0].detailProject.length) {
        dataForm.detailDProject = detailSelectRows.value[0].detailProject
      } else {
        getProjectVal({ current: 1, size: -1, projectId: dataForm.projectId, creditCode: dataForm.ownerCreditCode }).then((response) => {
          dataForm.detailDProject = response.data
          dataForm.detailDProject.map((item) => {
            item.amountDebtRepayment = ''
            item.amountReceivableBalanceAccounts = Number(item.amountPayable) - Number(item.amountPaid)
          })
          detailSelectRows.value[0].detailProject = dataForm.detailDProject
        })
      }
    })
  }
}

// 表单禁用逻辑：查看模式 / 非编辑中状态 / 非起始节点 / 无执行人
const FormDisabled = computed(() => {
  return showOperateType.value === 'view' ||
    (!route.query.nodeKey && dataForm.billStateId !== '0') ||
    (route.query.nodeKey && route.query.nodeKey !== startNodeKey.value) ||
    (route.query.nodeKey && !route.query.psmId) ||
    (route.query.mode && route.query.mode == 'view')
})

const billStateIdFormatter = (columnValue) => {
  const item = billStateIdOptions.value.find((item) => item.value === columnValue + '')
  return item ? item.label : ''
}

// 显示表单
const show = async (operateType: string, id?: string, data?: any, isProcessFunction?: any) => {
  showOperateType.value = operateType
  const activeFilter = operateType != 'view' ? '1' : ''
  billStateIdOptions = bill_state(activeFilter)
  debtProtocolTypeOptions = debt_protocol_type(activeFilter)
  contractDebtTermsFlagOptions = common_status(activeFilter)
  determinationBasisOffsetValueOptions = determination_basis_offset_value(activeFilter)
  assetClassOptions = debt_assets_type(activeFilter)
  transferFlagOptions = common_status(activeFilter)
  visible.value = true
  detailSelectRows.value = []
  await nextTick(() => {
    dataFormRef.value?.resetFields()
    componentKey.value += 1
  })
  Object.assign(dataForm, initForm)
  loading.value = true
  try {
    if (id) {
      getObj(id).then(async (res) => {
        Object.assign(dataForm, res.data)
        if (dataForm.billStateId == '4' && isProcessFunction == undefined)
          dataForm.isProcessData = await getIsProcessByBusinessId(id)
        else dataForm.isProcessData = isProcessFunction
        oldValue.value = operateType === 'view' ? null : JSON.stringify(dataForm)
        if (dataForm.detail.length > 0) {
          nextTick(() => { detailTable.value.toggleRowSelection(dataForm.detail[0], true) })
        }
      })
    } else {
      dataForm.version = '0'
      dataForm.businessType = '1'
      let res = await getProject({ financeState: 0 })
      if (res.length == 1) { projectMasterSelectProjectOkHandle(res[0]) }
    }
  } finally {
    loading.value = false
  }
}

const isSubmitShow = computed(() => !isProcessState.value && showOperateType.value !== 'view')

const gobackClick = () => {
  visible.value = false
  emit('goback', 'cancel')
}

// 折叠/展开切换
const handleToggleCollapseExpand = () => {
  if (activeFlag.value) {
    if (activeNames.value.length > 0) { activeNames.value = []; activeFlag.value = false }
    else { activeNames.value = collapseItemName }
  } else {
    if (activeNames.value.length === 0 || activeNames.value.length !== collapseItemName.length) {
      activeNames.value = collapseItemName; activeFlag.value = true
    } else { activeNames.value = [] }
  }
}

// 是否流程类状态
const isProcessState = computed(() => {
  if (!dataForm) return
  if (dataForm.billStateId == '0') return isProcessFunction.value
  if (dataForm.billStateId != '4') return true
  return dataForm.isProcessData
})

// 流转前校验并保存
const beforeFlow = async () => {
  const isNext = await checkData(false, 'process')
  if (isNext) {
    if (oldValue.value === JSON.stringify(dataForm)) return { cancel: false, data: dataForm }
    return postData({}, false).then((d) => ({ cancel: false, data: d }))
  }
  return { cancel: true }
}

const refreshDataForm = () => {
  getObj(dataForm.id).then((res) => {
    Object.assign(dataForm, res.data)
    oldValue.value = showOperateType.value === 'view' ? null : JSON.stringify(dataForm)
  })
}

const workflowPopClose = () => { refreshDataForm(); emit('refresh') }
const afterFlowHandle = () => { refreshDataForm(); gobackClick(); emit('refresh') }

// 子表数量校验
const detailCheckOneList = () => {
  if (dataForm.detail.length < 1) { useMessage().error(t(`column.${processDefKey}.detail.checkOneList`)); return false }
  return true
}
const detailDProjectCheckOneList = () => {
  if (dataForm.detailDProject.length < 1) { useMessage().error(t(`column.${processDefKey}.detailDProject.checkOneList`)); return false }
  return true
}

/**
 * 公共校验：保存时可跳过表单校验，提交/流转时执行表单校验+子表数量校验
 */
const checkData = async (isList = false, btnType = 'save') => {
  let isNext = true
  if (btnType === 'submit' || btnType === 'process') {
    isNext = await formValidate([{
      dataFormName: dataForm, name: dataFormRef,
      detailsName: [
        { listName: 'detail', rowName: t(`column.${processDefKey}.master.detailCollapseTitle`), rowNameType: 'label' },
        { listName: 'detailDProject', rowName: t(`column.${processDefKey}.master.detailDProjectCollapseTitle`), rowNameType: 'label' }
      ]
    }], isList)
    isNext = isNext && (await detailCheckOneList())
    isNext = isNext && (await detailDProjectCheckOneList())
  }
  return isNext
}

// 新增/修改接口调用
const postData = async (extVals = {}, isSave = false) => {
  loading.value = true
  try {
    const submitData = Object.assign({}, dataForm, {
      detail: dataForm.detail.map((x) => { if (x.id < 0) x.id = ''; return x })
    }, extVals)
    let res = dataForm.id ? await putObj(submitData) : await addObj(submitData)
    useMessage().success(dataForm.id ? t('common.editSuccessText') : t('common.addSuccessText'))
    Object.assign(dataForm, res.data)
    const query = route.query
    if (isSave && !query.taskId) {
      visible.value = false; emit('goback'); emit('refresh', 'save', dataForm)
    }
    return dataForm
  } finally {
    loading.value = false
  }
}

const saveClick = async (isSave = true, extVals = {}) => {
  let isNext = await checkData(false, 'save')
  if (!isNext) return false
  if (oldValue.value === JSON.stringify(dataForm)) { useMessage().info(t('message.no_changed_cannot_save')); return }
  postData(extVals, isSave)
}

const submitHandle = async (isBtn, isList?) => {
  if (!(await checkData(isList, 'submit'))) return
  useMessageBox().confirm(t('message.form_submit')).then(() => {
    Object.assign(dataForm, { tempProp: moment().format() })
    postData({ billStateId: '4', billState: '已完成' }, true)
  })
}

// 项目弹窗
const projectMasterSelectProjectClick = () => {
  ProjectMasterSelectProject.value.data.dialogVisible = true
  ProjectMasterSelectProject.value.data.searchParams = { financeState: 0 }
  ProjectMasterSelectProject.value.getDefalutTree()
}
const projectMasterSelectProjectOkHandle = (val) => {
  dataForm.projectName = val.projectShort
  dataForm.projectCode = val.projectCode
  dataForm.projectId = val.id
  dataForm.debtAmount = null; dataForm.detail = []; dataForm.detailDProject = []
  getOwner({ projectId: dataForm.projectId }).then((response) => {
    let data = response.data
    if (data.length == 1) {
      dataForm.ownerId = data[0].id; dataForm.owner = data[0].name; dataForm.ownerCreditCode = data[0].creditCode
    }
  })
}

// 业主弹窗
const ownerInfoRegSelectOwnerClick = () => {
  selectOwnerRef.value.data.dialogVisible = true
  selectOwnerRef.value.data.type = '1'
  selectOwnerRef.value.getDataList(dataForm.projectId)
}
const selectOwnerOkHandle = (data) => {
  dataForm.ownerId = data.id; dataForm.ownerCreditCode = data.creditCode; dataForm.owner = data.name
  dataForm.debtAmount = null; dataForm.detail = []; dataForm.detailDProject = []
}

const isOwnerDisabled = computed(() => {
  return FormDisabled.value || !dataForm.projectId
})

// 抵债金额计算：抵债金额 = 各资产拟抵入价值累加
const amountComputed = (event, row) => {
  row.amountDebtRepayment = event
  detailSelectRows.value[0].proposedOffsetValue = 0
  dataForm.debtAmount = 0
  dataForm.detailDProject.map((item) => { detailSelectRows.value[0].proposedOffsetValue += Number(item.amountDebtRepayment || 0) })
  dataForm.detail.map((item) => { dataForm.debtAmount += Number(item.proposedOffsetValue) })
}

const isAddDetailDisabled = computed(() => showOperateType.value === 'view' || !dataForm.projectName || !dataForm.owner)
const isDelDetailDisabled = computed(() => showOperateType.value === 'view' || detailSelectRows.value.length === 0)

onMounted(() => {
  getProcessFunction(route.path).then((res) => { isProcessFunction.value = res === '0' })
})

watch(() => dataForm, () => {
  saveBtn.value = false
  if (JSON.stringify(initForm) != JSON.stringify(dataForm) && oldValue.value != JSON.stringify(dataForm)) {
    saveBtn.value = true
  }
}, { deep: true, immediate: true })

defineExpose({ show, oldValue, showOperateType, dataFormRef, dataForm, submitHandle, beforeFlow, checkData })
</script>
