<script setup lang="tsx">
import { reactive, ref, unref } from 'vue';
import { TableData } from '@/api/csck/CsckWorkFlow/types';
import { useTable } from '@/hooks/web/useTable';
import { useI18n } from '@/hooks/web/useI18n';
import { Table, TableColumn } from '@/components/Table';
import { ElButton, ElLink, ElText } from 'element-plus';
import { Search } from '@/components/Search';
import { FormSchema } from '@/components/Form';
import { ContentWrap } from '@/components/ContentWrap';
import Approve from './components/Approve.vue';
import { Dialog } from '@/components/Dialog';
import { getWidth, randomCode } from '@/utils';
import { getRoleTreeApi } from '@/api/system/SysRole';
import { useRouter } from 'vue-router'
import { getDateByPrevMonth } from '@/utils/dateUtil';
import { STATE_DICT_LIST } from './constants';
import { getUserInfo } from '@/utils/auth';
import { filter } from 'lodash-es';
import { ElMessageBox } from 'element-plus'
import { getCsckBusinessSystemListApi, getCsckWorkFlowSubTable, saveCsckBusinessSystemApi } from '@/api/csck/CsckWorkFlow';
import TABLE_ID_CONST from '@/constants/table/table-id';

const TABLE_ID = TABLE_ID_CONST.BUSINESS.OA.HOME;
defineOptions({
  name: 'Home'
})

const userInfo = getUserInfo();

// 获取当前用户机构号
const loginOrganCode = userInfo.session_organCode;

// 获取登录Id
const loginId = userInfo.session_userId;

// 获取登录名
const loginName = userInfo.session_loginName;

// 获取系统组
const professionGroups = userInfo?.professionGroups?.map(item => item.proId);

// 获取系统组,转成map
const proSubmits = userInfo?.professionGroups.reduce((acc,cuur) =>{
  acc[cuur.proId]=cuur.proSubmit;
  return acc;
},{});
const { t } = useI18n();
const router = useRouter();
const date = getDateByPrevMonth();

const { tableRegister, tableState, tableMethods } = useTable({
  fetchInitParamsApi: async () => {
    searchParams.value = {
      dataDate: date,
      orgCode: loginOrganCode ? [loginOrganCode] : [],
      systemGroup: professionGroups,
    };
  },
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState;
    const res = await getCsckBusinessSystemListApi({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      sessionUserId: unref(loginId),
      ...unref(searchParams),
    });
    const list = res.body.list.map((item: TableData) => {
      item.randomCode = randomCode(32)
      if (item.grade) {
        item.hasChildren = true
      }
      return item
    });
    return {
      list: list,
      total: res.body.total,
    };
  },
});

const { loading, dataList, total, currentPage, pageSize } = tableState;
const { getList, refresh } = tableMethods;

const tableColumns = reactive<TableColumn[]>(
  [
    {
      field: 'selection',
      type: 'selection',
    },
    {
      field: 'systemGroup',
      label: '系统组',
      hidden:true
    },
    {
      field: 'systemGroupName',
      label: '系统组',
    },
    {
      field: 'organName',
      label: '机构',
    },
    {
      field: 'organCode',
      label: '机构',
      hidden:true
    },
    {
      field: 'dataDate',
      label: '数据日期',
      width: 160,
    },
    {
      field: 'createUser',
      label: '发起人',
    },
    {
      field: 'createTime',
      label: '发起时间',
    },
    {
      field: 'state',
      label: '状态',
      optionApi: async () => {
        return STATE_DICT_LIST;
      },
    },
    {
      field: 'action',
      label: t('tableDemo.action'),
      width: 160,
      fixed: 'right',
      slots: {
        default: (data: any) => {
          if (data.row.randomCode) {
            return (
              <>
                {data.row.state === '0' && proSubmits[data.row.systemGroup]==='1'
                  ?
                  <ElLink type="primary" disabled={btnLoading.value} underline={false} onClick={() => action(data.row, 'submit')}>
                        提交
                      </ElLink>
                  : null}
                <ElLink type="primary" underline={false} onClick={() => lookRule(data.row)}>
                  查看
                </ElLink>
                {(data.row.state === '1'||data.row.state === '2'||data.row.state === '3')&&(loginOrganCode==='990000'||loginOrganCode.indexOf('0098')!==-1)
                  ?
                  <ElLink type="primary" disabled={btnLoading.value} underline={false} onClick={() => action(data.row, 'rollback')}>
                    打回
                      </ElLink>
                  : null}
              </>
            )
          }
          // 已提交
          if (data.row.state === '1'||data.row.state === '2'||data.row.state === '3') {
            return (
              <>
                <ElLink type="primary" underline={false} onClick={() => action(data.row, 'reject')}>
                  打回
                </ElLink>
              </>
            )
          }
          return '';
        },
      },
    },
  ].map(item => ({ minWidth: item.label ? getWidth(item.label) : 120, ...item }) as TableColumn),
);

const searchSchema = reactive<FormSchema[]>([
  {
    field: 'systemGroup',
    label: '系统组',
    component: 'TreeSelect',
    optionApi: async () => {
      const res = await getRoleTreeApi({
        loginName
      });
      return res;
    },
    componentProps: {
      style: 'width: 100%',
      collapseTags: true,
      checkStrictly: true,
      multiple: true,
      showCheckbox: true,
      nodeKey: 'id',
      props: { children: 'childs', label: 'nodeName' },
    },
    value: professionGroups
  },
  {
    field: 'dataDate',
    label: '数据日期',
    componentProps: {
      type: 'date',
      valueFormat: 'YYYY-MM-DD'
    },
    component: 'DatePicker',
    value: date
  }
]);

const searchParams = ref({});
const setSearchParams = (data: any) => {
  searchParams.value = data;
  getList();
};

const dialogVisible = ref(false);
const dialogTitle = ref('');

const currentRow = ref();
const actionType = ref('');

const approveRef = ref<ComponentRef<typeof Approve>>();

/** 提交/打回操作 **/
const action = async (row: any, type: string) => {
  if (type === 'submit') {
    submitAction(row, type);
  }
  if (type === 'reject') {
    rejectAction(row, type);
  }
  if (type === 'rollback') {
    rollbackeAction(row, type);
  }
};

const btnLoading = ref(false);
const subProcList: any = ref([]);
/** 提交操作 **/
const submitAction = async (row: any, type: string) => {
  subProcList.value = [];
  // 前置检查
  if (row.hasChildren && (!row.children || !row.children.length)) {
    const formData = {
      ...unref(searchParams),
      organCode: row.organCode,
      systemGroup: row.systemGroup
    };
    btnLoading.value = true
    const res = await getCsckWorkFlowSubTable(formData)
    btnLoading.value = false
    if (res?.body?.list) {
      const data = res?.body?.list;
      row.children = data;
    }
  }
  // 下级机构未提交
  if (row.children) {
    const data = filter(row.children, { state: '0' });
    if (data && data.length) {
      subProcList.value = row.children;
      const list = data.map(item => item.organName);
      ElMessageBox.confirm(`<div style="max-height: 300px;overflow: auto;">${list.join('<br>')}</div>`, '以下机构尚未提交，确定要提交吗？', {
        confirmButtonText: t('common.ok'),
        cancelButtonText: t('common.cancel'),
        type: 'warning',
        dangerouslyUseHTMLString: true,
      }).then(async () => {
        dialogTitle.value = '提交';
        actionType.value = type;
        currentRow.value = row;
        dialogVisible.value = true;
      })
      return;
    }
  }
  // 下级机构已提交
  dialogTitle.value = '提交';
  actionType.value = type;
  currentRow.value = row;
  dialogVisible.value = true;
};

/** 打回操作 **/
const rejectAction = async (row: any, type: string) => {
  dialogTitle.value = '打回';
  actionType.value = type;
  currentRow.value = row;
  dialogVisible.value = true;
};

const lookRule = async (row: any) => {
  router.push(`/check/datacheckresult/${row.organCode}/${row.systemGroup}/${row.dataDate}`)
  // let detailLoading = ElLoading.service({
  //   background: 'rgba(0, 0, 0, 0.7)',
  // });
  // const res = await queryCsckBusinessSystemApi(row.systemGroup, row.systemVersion)
  //   .catch(() => {})
  //   .finally(() => {
  //     detailLoading.close();
  //   });
  // detailLoading.close();
  // if (res) {
  //   const data = res.body.result;

  //   router.push({
  //     name: 'datacheckresult',
  //     state:{
  //       params: {
  //         workFlowData: data
  //       }
  //     }
  //   })
  // }
};

const saveLoading = ref(false);

/** 提交/打回 **/
const save = async () => {
  const approve = unref(approveRef);
  const formData = await approve?.submit();
  if (formData) {
    const { processinsstanceId = '', taskId = '' } = formData;
    formData.processinsstanceId = processinsstanceId;
    formData.taskId = taskId;
    // 下级机构未提交
    if (unref(subProcList).length) {
      const _list = filter(unref(subProcList), { state: '1' });
      if (_list && _list.length) {
        formData.subProcTaskId = _list.map(item => item.processinsstanceId+'|'+item.taskId+'|'+item.organCode);
      }
    }
    saveLoading.value = true;
    const res = await saveCsckBusinessSystemApi(formData)
      .catch(() => {})
      .finally(() => {
        saveLoading.value = false;
      });
    if (res) {
      dialogVisible.value = false;
      currentPage.value = 1;
      getList();
    }
  }
};

const disabled = ref(true);

const onSelectionChange = (selection: TableData[]) => {
  disabled.value = selection.length === 0;
};

/** 数据加载 */
const load = async (
  row: TableData,
  __: any,
  resolve: (date: TableData[]) => void
) => {
  const formData = {
    ...unref(searchParams),
    organCode: row.organCode,
    systemGroup: row.systemGroup
  };
  const res = await getCsckWorkFlowSubTable(formData)
  if (res) {
    const data = res?.body?.list;
    resolve(data)
  }
}


const rollbackeAction= async (row: any, type: string) => {
   const formData = {
      ...unref(searchParams),
      organCode: row.organCode,
      systemGroup: row.systemGroup
    };

  subProcList.value = [];
  // 前置检查
  if (row.hasChildren && (!row.children || !row.children.length)) {
    btnLoading.value = true
    const res = await getCsckWorkFlowSubTable(formData)
    btnLoading.value = false
    if (res?.body?.list) {
      const data = res?.body?.list;
      row.children = data;
    }
  }
  // 下级机构未提交
  if (row.children) {
    const data = filter(row.children, { state: '2' });
    if (data && data.length) {
      const list = data.map(item => item.organName);
      const organCodes = data.map(item => item.code);
      formData.organCode=organCodes+","+formData.organCode;
      ElMessageBox.confirm(`<div style="max-height: 300px;overflow: auto;">${list.join('<br>')}</div>`, '以下机构尚已提交，确定要打回吗？', {
        confirmButtonText: t('common.ok'),
        cancelButtonText: t('common.cancel'),
        type: 'warning',
        dangerouslyUseHTMLString: true,
      }).then(async () => {
        saveLoading.value = true;
        const res = await saveCsckBusinessSystemApi(formData)
        .catch(() => {})
        .finally(() => {
        saveLoading.value = false;
          });
        if (res) {
          dialogVisible.value = false;
          currentPage.value = 1;
          getList();
          }
   })
      return;
    }
  }
};
</script>

<template>
  <ContentWrap>
    <Search :schema="searchSchema" @reset="setSearchParams" @search="setSearchParams" />

    <Table
      :table-id="TABLE_ID"
      :columns="tableColumns"
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :data="dataList"
      :border="true"
      :loading="loading"
      :pagination="{
        total
      }"
      @selection-change="onSelectionChange"
      @register="tableRegister"
      @refresh="refresh"
      node-key="systemGroup"
      row-key="randomCode"
      lazy
      :load="load"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Approve ref="approveRef" :current-row="currentRow" :action-type="actionType" />
    <template #footer>
      <ElButton type="primary" :loading="saveLoading" @click="save">
        {{ t('dialogDemo.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>
</template>

<style lang="less" scoped>
:deep(.el-select .el-select__tags > span) {
  display: inline-flex !important;
}
</style>
