<template>
  <!-- 项目资产抵入 -->
  <div class="layout-padding">
    <div class="layout-padding-auto layout-padding-view" v-show="visible">
      <!-- 按钮区域 -->
      <div class="menu_boxs">
        <div class="avue-crud__menu">
          <div class="avue-crud__left">
            <el-button icon="Plus" type="primary" v-auth="'financialcapital_DebtProjectAssetsOffset_add'" @click="inToFormClick('add')">
              {{ t('common.addBtn') }}
            </el-button>
            <el-button v-auth="'financialcapital_DebtProjectAssetsOffset_edit'" icon="EditPen" type="primary" class="ml10" :disabled="isEditDisabled" @click="inToFormClick('edit')">
              {{ t('common.editBtn') }}
            </el-button>
            <el-button v-auth="'financialcapital_DebtProjectAssetsOffset_view'" icon="View" type="primary" :disabled="isViewDisabled" @click="inToFormClick('view')">
              {{ t('common.viewBtn') }}
            </el-button>
            <el-button v-auth="'financialcapital_DebtProjectAssetsOffset_del'" icon="Delete" type="primary" :disabled="isDeleteDisabled" @click="handleDelete">
              {{ t('common.delBtn') }}
            </el-button>
            <el-button v-if="!isSubmitAndProcessShow" v-auth="'financialcapital_DebtProjectAssetsOffset_edit'" icon="Select" type="primary" :disabled="isSubmitDisabled" @click="submitHandle">
              {{ t('common.submit') }}
            </el-button>
            <process v-if="isSubmitAndProcessShow" v-auth="'financialcapital_DebtProjectAssetsOffset_edit'" :disabled="isProcessDisabled" :currentRow="selectObjs[0]" :beforeFlow="beforeFlow" @workflowPopClose="workflowPopClose" @afterFlowHandle="afterFlowHandle"></process>
            <el-button :disabled="state?.dataList?.length == 0" type="primary" icon="Download" @click="openDialog">
              {{ t('common.exportBtn') }}
            </el-button>
          </div>
          <div class="avue-crud__right d-flex j-end a-center button_box">
            <!-- 智能搜索 -->
            <el-tooltip class="item" effect="dark" popper-class="tooltipWidth" :content="searchKeywordTooltip" placement="bottom-end">
              <el-input v-model="state.userQueryForm.smartVal" :placeholder="searchKeywordTooltip" style="width: 300px" maxlength="100" @change="currentChangeHandle(1)" @keyup.enter="currentChangeHandle(1)"></el-input>
            </el-tooltip>
            <el-button icon="el-icon-search" type="primary" @click="currentChangeHandle(1)">{{ t('common.searchBtn') }}</el-button>
            <CustomQuery ref="customQuery" :options="state.userQueryConfig" @goback="userQueryGobackHandle" />
            <el-button circle size="small" icon="Refresh" @click="getDataList(1)"></el-button>
            <el-button circle size="small" icon="Operation" @click="showDrawer"></el-button>
          </div>
        </div>
      </div>
      <!-- 表格区域 -->
      <div class="table_h">
        <basic-container>
          <el-table :data="state.dataList" v-loading="state.loading" ref="valueTable" row-key="id"
            :row-class-name="({ row }) => (selectObjs.find((item) => item.id === row.id) ? 'selectRowColor' : '')"
            :header-cell-style="tableStyle.headerCellStyle" @selection-change="selectionChangHandle"
            @row-click="currentRowChangeHandle" @sort-change="sortChangeHandle">
            <el-table-column type="selection" class-name="no-dragging" fixed width="40" align="center" />
            <el-table-column type="index" fixed class-name="no-dragging" :label="t('common.serial')" width="80" align="center" />
            <template v-for="(column, index) in columns.filter((c) => c.show)" :key="column.key + index">
              <el-table-column :prop="column.key" :label="t(`column.${processDefKey}.master.${column.key}`)"
                :min-width="column.width" :fixed="column.fixed" :class-name="column.fixed ? 'no-dragging' : ''"
                show-overflow-tooltip align="center" :formatter="format" />
            </template>
          </el-table>
          <pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" v-bind="state.pagination" />
        </basic-container>
      </div>
    </div>
    <DetailForm ref="form" @refresh="formGobackHandle" @goback="cancel" />
    <TableColumnDrawer ref="tableColumnDrawer" :columns="columns" />
    <ExportExcel ref="exportExcel"></ExportExcel>
    <CirculationForm ref="CirculationFormRef"></CirculationForm>
  </div>
</template>
<script setup lang="ts" name="DebtProjectAssetsOffset">
import { useI18n } from 'vue-i18n'
const { t } = useI18n()
import { provide } from 'vue'
import { useMessage, useMessageBox } from '/@/hooks/message'
import { BasicTableProps, useTable, dynamicsShowColumn, useTableColumnDrag } from '/@/hooks/table'
import { dataMasterEntity, filterTypes } from './options'
import { fetchList, delObjs, getObj } from '/@/api/financialcapital/DebtProjectAssetsOffset'
import { getProcessFunction, getIsProcessByBusinessId, getMenuObjByMenuPath, getCurrPsmInfo } from '/@/util/util'
import { formatMoney } from '/@/utils/formatMoney'
import { inputNumber } from '/@/utils/inputNumber'
import { validateNull } from '/@/utils/validate'
import { bill_state, debt_protocol_type, common_status, determination_basis_offset_value, debt_assets_type } from '/@/enums/dict'

const DetailForm = defineAsyncComponent(() => import('./form.vue'))
const TableColumnDrawer = defineAsyncComponent(() => import('/@/components/TableColumnDrawer/index.vue'))
const CustomQuery = defineAsyncComponent(() => import('/@/components/CustomQuery/index.vue'))

const columns = ref([] as any[])
const form = ref()
const tableColumnDrawer = ref()
const customQuery = ref()
const visible = ref(true)
const valueTable = ref()
const selectObjs = ref([]) as any
const multiple = ref(true)
const exportExcel = ref()
const route = useRoute()
const processDefKey = getMenuObjByMenuPath(route.path).modelId
const isProcessFunction = ref(false)
const CirculationFormRef = ref()

// 初始化字典选项
const billStateIdOptions = bill_state()
const debtProtocolTypeOptions = debt_protocol_type()
const contractDebtTermsFlagOptions = common_status()
const determinationBasisOffsetValueOptions = determination_basis_offset_value()

const state: BasicTableProps = reactive<BasicTableProps>({
  tableRef: valueTable,
  queryForm: { businessType: '1' },
  userQueryConfig: {
    entity: dataMasterEntity,
    dictOptions: [
      { propLabel: t(`column.${processDefKey}.master.billStateId`), propName: 'billStateId', propVals: [], propCheckVals: [], datas: billStateIdOptions },
      { propLabel: t(`column.${processDefKey}.master.debtProtocolType`), propName: 'debtProtocolType', propVals: [], propCheckVals: [], datas: debtProtocolTypeOptions },
      { propLabel: t(`column.${processDefKey}.master.contractDebtTermsFlag`), propName: 'contractDebtTermsFlag', propVals: [], propCheckVals: [], datas: contractDebtTermsFlagOptions },
      { propLabel: t(`column.${processDefKey}.master.determinationBasisOffsetValue`), propName: 'determinationBasisOffsetValue', propVals: [], propCheckVals: [], datas: determinationBasisOffsetValueOptions }
    ],
    timePropName: 'createTime',
    timeSelectedLabel: '全部',
    timeSelectedTimeRange: [],
    queryItems: []
  },
  userQueryForm: {
    filterTypes: filterTypes,
    smartNames: Object.keys(dataMasterEntity).filter((item) => dataMasterEntity[item].smart),
    smartVal: '',
    orderBy: ['createTime:desc']
  },
  pageList: fetchList,
  columns: columns,
  exportExcel: exportExcel,
  url: '/pmfi/debtProjectAssetsOffset/export'
})
state.userQueryConfig?.dictOptions?.forEach((dict) => (dict.propCheckVals = dict.propVals))

const { getDataList, currentChangeHandle, sizeChangeHandle, sortChangeHandle, tableStyle, openDialog } = useTable(state)
dynamicsShowColumn(columns, dataMasterEntity, 0, route.path)
useTableColumnDrag(columns)

const showDrawer = () => {
  tableColumnDrawer.value.fiexdColumnCount = 0
  tableColumnDrawer.value.show()
}

// 字典格式化映射：字段名 -> 对应的选项数据
const dictFormatterMap = {
  billStateId: billStateIdOptions,
  debtProtocolType: debtProtocolTypeOptions,
  contractDebtTermsFlag: contractDebtTermsFlagOptions,
  determinationBasisOffsetValue: determinationBasisOffsetValueOptions
}
// 金额字段集合
const moneyFields = ['debtAmount', 'amountDebtRepayment', 'amountContract', 'amountConfirmed', 'amountContractReceivable', 'amountReceived', 'amountReceivableBalanceAccounts', 'amountOverdueAccountsReceivable']

/** 表格列格式化 */
const format = (row, column, cellValue, index) => {
  if (validateNull(cellValue)) return ''
  // 字典类字段：从对应选项中查找label
  const dictOptions = dictFormatterMap[column.property]
  if (dictOptions) {
    const item = dictOptions.value.find((item) => item.value == cellValue + '')
    return item ? item.label : ''
  }
  // 金额类字段：统一格式化为货币
  if (moneyFields.includes(column.property)) {
    return cellValue ? formatMoney(inputNumber(String(cellValue))) + t('common.yuan') : '0' + t('common.yuan')
  }
  return cellValue
}

// 编辑按钮禁用：必须选中1条编辑中(billStateId=0)且为当前用户创建的数据
const isEditDisabled = computed(() => {
  return selectObjs.value.length !== 1 || !selectObjs.value[0] ||
    selectObjs.value[0].billStateId !== '0' || selectObjs.value[0].createUserId !== getCurrPsmInfo().userId
})

const isViewDisabled = computed(() => selectObjs.value.length !== 1)

// 删除按钮禁用：同编辑逻辑
const isDeleteDisabled = computed(() => {
  return selectObjs.value.length === 0 || selectObjs.value.length != 1 ||
    selectObjs.value.some((item) => item.billStateId !== '0') ||
    selectObjs.value[0].createUserId !== getCurrPsmInfo().userId
})

// 提交按钮禁用：同删除逻辑
const isSubmitDisabled = computed(() => {
  return selectObjs.value.length === 0 || selectObjs.value.length != 1 ||
    selectObjs.value.some((item) => item.billStateId !== '0') ||
    selectObjs.value[0].createUserId !== getCurrPsmInfo().userId
})

// 流转按钮禁用：可选多条但须为编辑中状态的自己创建的数据
const isProcessDisabled = computed(() => {
  return selectObjs.value.length === 0 ||
    selectObjs.value.some((item) => item.billStateId !== '0') ||
    selectObjs.value[0].createUserId !== getCurrPsmInfo().userId
})

// 提交/流转按钮显隐：根据单据状态和菜单配置决定显示提交还是流转
const isSubmitAndProcessShow = computed(() => {
  if (selectObjs.value.length === 0 || selectObjs.value.length > 1) return isProcessFunction.value
  const firstObj = selectObjs.value[0]
  if (firstObj.billStateId == '0') return isProcessFunction.value
  if (firstObj.billStateId != '4') return true
  return firstObj.isProcessData
})

// 智能搜索提示
const searchKeywordTooltip = computed(() => {
  return `${t('message.provide_search_keyword')}: ${Object.values(columns.value)
    .filter((item) => item.smart)
    .map((item) => `${t(`column.${processDefKey}.master.${item.key}`)}`)
    .join(', ')}`
})

const selectionChangHandle = (objs: []) => {
  selectObjs.value = objs
  multiple.value = !objs.length
}

const currentRowChangeHandle = async (row) => {
  selectObjs.value = []
  valueTable.value.clearSelection()
  selectObjs.value.push(row)
  // 已完成状态的数据需异步获取是否流程类
  if (selectObjs.value[0] && selectObjs.value[0].billStateId == '4' && selectObjs.value[0].isProcessData == undefined) {
    selectObjs.value[0]['isProcessData'] = await getIsProcessByBusinessId(selectObjs.value[0].id)
  }
  nextTick(() => {
    valueTable.value.toggleRowSelection(row, true)
  })
}

const handleDelete = async () => {
  const ids = selectObjs.value.map((item) => item.id)
  try {
    await useMessageBox().confirm(t('common.delConfirmText'))
  } catch {
    return
  }
  await delObjs(ids)
  getDataList(1)
  useMessage().success(t('common.delSuccessText'))
}

const inToFormClick = (operateType: string) => {
  visible.value = false
  const id = operateType === 'add' ? undefined : selectObjs.value[0].id
  form.value.show(operateType, id, {}, selectObjs.value[0] ? selectObjs.value[0].isProcessData : isProcessFunction)
}

const formGobackHandle = (operateType: string, data: any) => {
  Object.assign(state.queryForm)
  getDataList(1)
}

const cancel = () => {
  visible.value = true
}

const userQueryGobackHandle = (queryObj, timeSelectedTimeRange: String[]) => {
  state.userQueryConfig && (state.userQueryConfig.timeSelectedTimeRange = timeSelectedTimeRange)
  state.userQueryConfig && (state.userQueryConfig.dictOptions = queryObj.dictOptions)
  state.userQueryForm && (state.userQueryForm.customFilters = queryObj.customFilters)
  state.userQueryForm && (state.userQueryForm.conditionFormat = queryObj.conditionFormat)
  getDataList(1)
}

// 路由携带businessKey时自动打开表单
const updatePageFun = () => {
  const query = route.query
  if (query.businessKey) {
    visible.value = false
    nextTick(() => {
      setTimeout(() => {
        form.value?.show(query.mode === 'view' ? 'view' : 'edit', query.businessKey)
      }, 500)
    })
  }
}

// 提交：获取最新数据后调用form页提交
const submitHandle = async () => {
  getObj(selectObjs.value[0].id).then(async (response) => {
    form.value.oldValue = JSON.stringify(response.data)
    form.value.operateType = 'edit'
    Object.assign(form.value.dataForm, response.data)
    nextTick(() => {
      form.value.submitHandle(true, true)
    })
  })
}

// 流转前：获取最新数据并校验
const beforeFlow = () => {
  return getObj(selectObjs.value[0].id).then((response) => {
    form.value.showOperateType = 'edit'
    form.value.oldValue = JSON.stringify(response.data)
    Object.assign(form.value.dataForm, response.data)
    return nextTick(async () => {
      if (!(await form.value.checkData(true, 'process'))) {
        return { cancel: true }
      }
      return { cancel: false, data: response.data }
    })
  })
}

const workflowPopClose = () => { getDataList(1) }
const afterFlowHandle = () => { getDataList(1) }

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

watch(() => route.fullPath, (newValue: any) => { updatePageFun() }, { immediate: true })
</script>
