<template>
  <div style="height: 100%">
    <w-grid
      ref="rebirthGridRef"
      title="违约重生列表"
      :fetch-data-url="Environment.apiContextPath('api/irbs/defaultRebirth/query')"
      :sort-no="true"
      :checkbox-selection="false"
      :query-form-cols-num="4"
      :query-form-fields="rebirthGrid.queryFormFields"
      :columns="rebirthGrid.columns"
      :toolbar-actions="rebirthGrid.buttons"
      :pagination="{
        sortBy: 'lastModifyDate',
        descending: true,
      }"
      :query-criteria="{
        fieldName: 'defaultRebornType',
        operator: 'equals',
        value: '02',
      }"
    ></w-grid>
    <w-dialog
      ref="rebirthLaunchDialogRef"
      title="新增申请"
      width="80%"
      height="80%"
      :buttons="[
        {
          label: '确定',
          icon: 'beenhere',
          click: launchRebirth,
        },
      ]"
    >
      <w-grid
        ref="custGridRef"
        title="客户信息列表"
        :fetch-data-url="Environment.apiContextPath('api/irbs/defaultCognizance')"
        :sort-no="true"
        :checkbox-selection="false"
        :query-form-cols-num="2"
        :config-button="false"
        :query-form-fields="[
          { name: 'custNo', label: '客户号', type: 'text' },
          { name: 'custName', label: '客户名称', type: 'text' },
        ]"
        :columns="[
          { name: 'custNo', label: '客户号' },
          { name: 'custName', label: '客户名称' },
          { name: 'effectiveDate', label: '违约日期', format: Formater.dateOnly() },
          {
            name: 'defaultProcessStatus',
            label: '状态',
            format: (val, row) => {
              if (row.defaultType === '02') {
                return '人工认定违约';
              }
              return '系统认定违约';
            },
          },
        ]"
        :toolbar-actions="['query', 'reset']"
        :query-criteria="{
          fieldName: 'valid',
          operator: 'equals',
          value: '1',
        }"
      ></w-grid>
    </w-dialog>
    <RebirthDialog ref="rebirthDialogRef" @refresh="refreshTable"></RebirthDialog>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { useQuasar } from 'quasar';
import { Environment, EnumTools, DictionaryTools, Options, Formater, axios, NotifyManager } from 'platform-core';
import RebirthDialog from './RebirthDialog.vue';
import { DefaultProcessStatus } from './DefaultManager.ts';

const $q = useQuasar();
const custGridRef = ref();
const rebirthGridRef = ref();
const rebirthLaunchDialogRef = ref();
const rebirthDialogRef = ref();

const DefaultProcessStatusEnum = await EnumTools.fetch('irbs.defaultManager.enums.DefaultProcessStatus');

const rebirthGrid = {
  buttons: [
    ['query', 'separator', 'moreQuery'],
    'reset',
    'separator',
    {
      extend: 'add',
      label: '新增申请',
      click: () => {
        rebirthLaunchDialogRef.value.show();
      },
    },
    {
      extend: 'edit',
      label: '编辑',
      enableIf: (args) => {
        if (
          args.selected &&
          (args.selected['rebirthProcessStatus'] === DefaultProcessStatus.TO_BE_SUBMITTED ||
            args.selected['rebirthProcessStatus'] === DefaultProcessStatus.RETURNED)
        ) {
          return true;
        }
        return false;
      },
      click: (args) => {
        rebirthDialogRef.value.show(args.selected);
      },
    },
    // {
    //   name: 'cancel',
    //   icon: 'delete_forever',
    //   label: '撤销',
    //   click: () => {},
    // },
    // {
    //   name: 'approval',
    //   icon: 'approval',
    //   label: '审批',
    //   click: () => {},
    // },
    'separator',
    {
      extend: 'view',
      click: (args) => {
        rebirthDialogRef.value.show(args.selected, true);
      },
    },
    'separator',
  ],
  queryFormFields: [
    { label: '申请编号', name: 'id', type: 'text' },
    { label: '客户号', name: 'custNo', type: 'text' },
    { label: '客户名称', name: 'custName', type: 'text' },
    { label: '流程状态', name: 'status', type: 'select', options: Options.enum(DefaultProcessStatusEnum) },
  ],
  columns: [
    { name: 'id', label: '申请编号' },
    { name: 'custNo', label: '客户号' },
    { name: 'custName', label: '客户名称' },
    { name: 'rebirthEffectiveDate', label: '重生生效时间', format: Formater.dateOnly() },
    { name: 'invalidDate', label: '重生失效时间', format: Formater.dateOnly() },
    { name: 'creator', label: '发起人' },
    { name: 'createDate', label: '重生发起时间', format: Formater.dateOnly() },
    {
      name: 'isValid',
      label: '是否重生',
      format: (val) => {
        if (val && val === '1') {
          return '是';
        }
        return '否';
      },
    },
    { name: 'rebirthProcessStatus', label: '流程状态', format: Formater.enum(DefaultProcessStatusEnum) },
    {
      name: 'defaultRebornType',
      label: '重生类型',
      format: (val) => {
        if (val && val === '02') {
          return '人工重生';
        }
        return '系统重生';
      },
    },
    { name: 'assignee', label: '当前任务人' },
  ],
};

const launchRebirth = async () => {
  const row = custGridRef.value.getSelectedRow();
  if (!row) {
    NotifyManager.error('请选择客户信息后记录后发起申请');
    return;
  }
  // 查询是否有在途流程
  const urlSearchParams = new URLSearchParams();
  urlSearchParams.append(
    'criteria',
    JSON.stringify({
      operator: 'and',
      criteria: [
        {
          fieldName: 'custNo',
          operator: 'equals',
          value: row['custNo'],
        },
        {
          fieldName: 'rebirthProcessStatus',
          operator: 'inSet',
          value: [DefaultProcessStatus.TO_BE_SUBMITTED, DefaultProcessStatus.RETURNED, DefaultProcessStatus.TO_BE_CHECKED],
        },
      ],
    }),
  );
  const resp = await axios.get(Environment.apiContextPath('api/irbs/defaultRebirth?pageable=false'), { params: urlSearchParams }).catch((error) => {
    console.info('error-------------', error);
  });
  if (resp.data?.content && resp.data.content.length > 0) {
    NotifyManager.warn('当前客户存在进行中违约重生流程');
    return;
  } else {
    // 发起
    axios
      .post(Environment.apiContextPath('api/irbs/defaultManager/rebirthApply'), { cognizanceId: row['id'], type: 'F' })
      .then((resp) => {
        if (resp && resp['code'] === 200 && resp['data']) {
          rebirthLaunchDialogRef.value.hide();
          refreshTable();
        }
      })
      .catch((error) => {
        console.info('error-------------', error);
      });
  }
};

const refreshTable = () => {
  rebirthGridRef.value.refresh();
};
</script>
