<template>
  <div>
    <div class="jeecg-basic-table-form-container" @keyup.enter="searchQuery">
      <a-form :model="queryParam" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-row :gutter="24">
          <a-col :lg="6">
            <a-form-item :label="searchFormSchema[0].label">
              <JInput placeholder="请输入" v-model:value="queryParam[searchFormSchema[0].field]" />
            </a-form-item>
          </a-col>
          <a-col :lg="6">
            <a-form-item :label="searchFormSchema[1].label">
              <JSearchSelect placeholder="请选择" v-model:value="queryParam[searchFormSchema[1].field]" dict="problemSourceFlag" />
            </a-form-item>
          </a-col>
          <a-col :lg="6">
            <a-form-item :label="searchFormSchema[2].label">
              <JSearchSelect placeholder="请选择" v-model:value="queryParam[searchFormSchema[2].field]" dict="assin_status" />
            </a-form-item>
          </a-col>
          <a-col :lg="6">
            <a-form-item>
              <a-space :size="5">
                <a-button type="primary" preIcon="ant-design:search-outlined" @click="searchQuery">查询</a-button>
                <a-button type="primary" preIcon="ant-design:reload-outlined" @click="searchReset">重置</a-button>
              </a-space>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <!--引用表格-->
      <BasicTable
        @register="registerTable"
        :rowSelection="rowSelection"
        :expandedRowKeys="expandedRowKeys"
        @expand="handleExpand"
        @fetch-success="onFetchSuccess"
      >
        <!--插槽:table标题-->
        <template #tableTitle>
          <a-button
            type="primary"
            @click="handleCreate"
            preIcon="ant-design:plus-outlined"
            v-if="hasPermission('rectify.assin:st_problem_task_assin:addProblem')"
          >
            新增问题</a-button
          >
          <!-- <a-button type="primary" @click="goToProblem"  v-if="hasPermission('rectify.assin:st_problem_task_assin:importProblem')"> 问题库导入</a-button> -->
          <!-- <a-button type="primary" @click="projectImport" v-if="hasPermission('rectify.assin:st_problem_task_assin:importProject')"> 项目导入</a-button> -->
          <a-button @click="handleBatchFp"> 批量分配</a-button>
          <a-button v-show="showUpBtn" type="primary" preIcon="ant-design:export-outlined" @click="onExportXls"> 导出</a-button>
          <j-upload-button v-show="showUpBtn" type="primary" preIcon="ant-design:import-outlined" @click="onImportXls">导入</j-upload-button>
          <a-button
            type="primary"
            @click="batchHandleDelete"
            v-if="hasPermission('rectify.assin:st_problem_task_assin:importProject')"
            v-show="selectedRowKeys.length > 0 && showUpBtn"
            >批量删除</a-button
          >
        </template>
        <!--操作栏-->
        <template #action="{ record }">
          <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)" />
        </template>
        <!--字段回显插槽-->
        <template #htmlSlot="{ text }">
          <div v-html="text"></div>
        </template>
        <!--省市区字段回显插槽-->
        <template #pcaSlot="{ text }">
          {{ getAreaTextByCode(text) }}
        </template>
        <template #fileSlot="{ text }">
          <span v-if="!text" style="font-size: 12px; font-style: italic">无文件</span>
          <a-button v-else :ghost="true" type="primary" preIcon="ant-design:download-outlined" size="small" @click="downloadFile(text)"
            >下载</a-button
          >
        </template>
      </BasicTable>
      <!--字典弹窗-->
      <StProblemTaskAssinModal @register="registerModal" @success="handleSuccess" />
      <StProblemTaskAssinModalFp @register="registerModalFp" @success="handleSuccess" />
      <StProblemTaskAssinModalJs @register="registerModalJs" @success="handleSuccess" />
      <StProblemTaskAssinModalEdit @register="registerModalEdit" @success="handleSuccess" />
      <StProblemTaskAssinModalSub @register="registerModalSub" @success="handleSuccess" />
      <StProblemTaskAssinModalDetail @register="registerModalDetail" @success="handleSuccess" />
      <StProblemTaskAssinModalBatchFp @register="registerModalBatchFp" @success="handleSuccess" />
      <StProblemTaskImport @register="registerModalImport" @success="handleSxSuccess" />
    </div>
  </div>
</template>

<script lang="ts" name="rectify.assin-stProblemTaskAssin" setup>
  //ts语法
  import { message } from 'ant-design-vue';
  import { reactive, ref, toRaw, unref } from 'vue';
  import { useRouter } from 'vue-router';
  import {
    batchDeleteStProblemTaskAssin,
    deleteStProblemTaskAssin,
    getChildList,
    getChildListBatch,
    getExportUrl,
    getImportUrl,
    list,
  } from './StProblemTaskAssin.api';
  import { columns, searchFormSchema } from './StProblemTaskAssin.data';
  import StProblemTaskAssinModal from './components/StProblemTaskAssinModal.vue';
  import StProblemTaskAssinModalBatchFp from './components/StProblemTaskAssinModalBatchFp.vue';
  import StProblemTaskAssinModalDetail from './components/StProblemTaskAssinModalDetail.vue';
  import StProblemTaskAssinModalEdit from './components/StProblemTaskAssinModalEdit.vue';
  import StProblemTaskAssinModalFp from './components/StProblemTaskAssinModalFp.vue';
  import StProblemTaskAssinModalJs from './components/StProblemTaskAssinModalJs.vue';
  import StProblemTaskAssinModalSub from './components/StProblemTaskAssinModalSub.vue';
  import StProblemTaskImport from './components/StProblemTaskImport.vue';
  import { JInput, JSearchSelect } from '/@/components/Form';
  import { useModal } from '/@/components/Modal';
  import { BasicTable, TableAction } from '/@/components/Table';
  import { useListPage } from '/@/hooks/system/useListPage';
  import { useUserStore } from '/@/store/modules/user';
  import { downloadFile } from '/@/utils/common/renderUtils';
  import { usePermission } from '/@/hooks/web/usePermission';

  const { hasPermission } = usePermission();

  const expandedRowKeys = ref([]);
  const showUpBtn = ref(true);
  const router = useRouter();
  //字典model
  const [registerModal, { openModal }] = useModal();
  const [registerModalFp, { openModal: openModalFp }] = useModal();
  const [registerModalJs, { openModal: openModalJs }] = useModal();
  const [registerModalEdit, { openModal: openModalEdit }] = useModal();
  const [registerModalSub, { openModal: openModalSub }] = useModal();
  const [registerModalDetail, { openModal: openModalDetail }] = useModal();
  const [registerModalBatchFp, { openModal: openModalBatchFp }] = useModal();
  const [registerModalImport, { openModal: openModalImport }] = useModal();
  const userStore = useUserStore();
  //注册table数据
  const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
    tableProps: {
      api: list,
      title: '任务分配',
      columns,
      canResize: false,
      useSearchForm: false,
      isTreeTable: true,
      formConfig: {
        //labelWidth: 120,
        schemas: searchFormSchema,
        autoSubmitOnEnter: true,
        showAdvancedButton: true,
        fieldMapToNumber: [],
        fieldMapToTime: [],
      },
      actionColumn: {
        width: 300,
        fixed: 'right',
      },
      beforeFetch(params) {
        params = Object.assign(params, { column: 'createdTime', order: 'desc' });
      },
    },
    exportConfig: {
      name: '任务分配',
      url: getExportUrl,
    },
    importConfig: {
      url: getImportUrl,
      success: importSuccess,
    },
  });

  const [
    registerTable,
    { reload, setProps, expandAll, collapseAll, updateTableDataRecord, findTableDataRecord, getDataSource },
    { rowSelection, selectedRowKeys },
  ] = tableContext;
  const labelCol = reactive({
    xs: { span: 24 },
    sm: { span: 8 },
  });
  const wrapperCol = reactive({
    xs: { span: 24 },
    sm: { span: 16 },
  });
  const queryParam = reactive({});
  function initParam() {
    const schemas = unref(searchFormSchema);
    schemas.forEach((item) => {
      queryParam[item.field] = '';
    });
  }
  initParam();
  function searchQuery() {
    setProps({ searchInfo: toRaw(queryParam) });
    reload();
  }
  function searchReset() {
    initParam();
    reload();
  }
  function goToProblem() {
    router.push({ path: '/standardlib/problem' });
  }
  /***
   * 项目导入
   */
  function projectImport() {
    openModalImport(true, {
      record: {},
      isUpdate: false,
    });
  }
  /**
   * 新增事件
   */
  function handleCreate() {
    let record = {};
    //专项检查
    record['problemSourceFlag'] = '2';
    // 未分配
    record['assinStatus'] = '0';
    openModal(true, {
      record,
      isUpdate: false,
    });
  }
  /**
   * 批量分配 todo
   */
  function handleBatchFp() {
    const ids = selectedRowKeys.value.filter((item) => !(item + '').includes('load'));
    console.log(ids);
    if (!ids || ids.length == 0) {
      message.error('请选择任务');
      return;
    }
    openModalBatchFp(true, {
      record: { ids: ids },
      isUpdate: true,
    });
  }
  /**
   * 编辑事件
   */
  async function handleEdit(record) {
    openModalEdit(true, {
      record,
      isUpdate: true,
    });
  }
  /**
   * 分配事件
   */
  async function handleEditFp(record) {
    openModalFp(true, {
      record,
      isUpdate: true,
    });
  }

  /**
   * 接收事件
   */
  async function handleEditJs(record) {
    openModalJs(true, {
      record,
      isUpdate: true,
    });
  }

  /**
   * 详情
   */
  async function handleDetail(record) {
    openModalDetail(true, {
      record,
      isUpdate: true,
      hideFooter: true,
    });
  }

  /**
   * 删除事件
   */
  async function handleDelete(record) {
    await deleteStProblemTaskAssin({ id: record.id }, importSuccess);
  }

  /**
   * 批量删除事件
   */
  async function batchHandleDelete() {
    const ids = selectedRowKeys.value;
    await batchDeleteStProblemTaskAssin({ id: ids }, importSuccess);
  }
  /**
   * 导入
   */
  function importSuccess() {
    (selectedRowKeys.value = []) && reload();
  }
  /**
   * 添加下级
   */
  function handleAddSub(record) {
    let data = JSON.parse(JSON.stringify(record));
    let newRecord = Object.assign(data, {
      id: null,
      pid: record.id,
      severity: null,
      priorityFlag: null,
      lateFinishTime: null,
      assinStatus: '0',
      receiveStatus: null,
    });
    openModalSub(true, {
      record: newRecord,
      isUpdate: false,
    });
  }
  async function handleSxSuccess() {
    reload();
  }
  /**
   * 成功回调
   */
  async function handleSuccess({ isUpdate, values, expandedArr, changeParent }) {
    if (isUpdate) {
      if (changeParent) {
        reload();
      } else {
        // 编辑回调
        updateTableDataRecord(values.id, values);
        reload();
      }
    } else {
      if (!values['id'] || !values['pid']) {
        //新增根节点
        reload();
      } else {
        //新增子集
        expandedRowKeys.value = [];
        for (let key of unref(expandedArr)) {
          await expandTreeNode(key);
        }
      }
    }
  }

  /**
   * 接口请求成功后回调
   */
  function onFetchSuccess(result) {
    getDataByResult(result.items) && loadDataByExpandedRows();
    //getDataByResult(result.items);
    // 树形展开有问题，目前需求文档没写不展开
    // setTimeout(() => {
    //   loadDataByExpandedRows()
    //   nextTick(expandAll)
    // }, 800);
  }
  /**
   * 根据已展开的行查询数据（用于保存后刷新时异步加载子级的数据）
   */
  async function loadDataByExpandedRows() {
    if (unref(expandedRowKeys).length > 0) {
      const res = await getChildListBatch({ parentIds: unref(expandedRowKeys).join(',') });
      if (res.success && res.result.records.length > 0) {
        //已展开的数据批量子节点
        let records = res.result.records;
        const listMap = new Map();
        for (let item of records) {
          let pid = item['pid'];
          if (unref(expandedRowKeys).includes(pid)) {
            let mapList = listMap.get(pid);
            if (mapList == null) {
              mapList = [];
            }
            mapList.push(item);
            listMap.set(pid, mapList);
          }
        }
        let childrenMap = listMap;
        let fn = (list) => {
          if (list) {
            list.forEach((data) => {
              if (unref(expandedRowKeys).includes(data.id)) {
                data.children = getDataByResult(childrenMap.get(data.id));
                fn(data.children);
              }
            });
          }
        };
        fn(getDataSource());
      }
    }
  }
  /**
   * 处理数据集
   */
  function getDataByResult(result) {
    if (result && result.length > 0) {
      return result.map((item) => {
        //判断是否标记了带有子节点
        if (item['hasChild'] == '1') {
          let loadChild = { id: item.id + '_loadChild', name: 'loading...', isLoading: true };
          item.children = [loadChild];
        }
        return item;
      });
    }
  }
  /**
   *树节点展开合并
   * */
  async function handleExpand(expanded, record) {
    // 判断是否是展开状态，展开状态(expanded)并且存在子集(children)并且未加载过(isLoading)的就去查询子节点数据
    if (expanded) {
      expandedRowKeys.value.push(record.id);
      if (record.children.length > 0 && !!record.children[0].isLoading) {
        let result = await getChildList({ pid: record.id });
        result = result.records ? result.records : result;
        if (result && result.length > 0) {
          record.children = getDataByResult(result);
        } else {
          record.children = null;
          record.hasChild = '0';
        }
      }
    } else {
      let keyIndex = expandedRowKeys.value.indexOf(record.id);
      if (keyIndex >= 0) {
        expandedRowKeys.value.splice(keyIndex, 1);
      }
    }
  }
  /**
   *操作表格后处理树节点展开合并
   * */
  async function expandTreeNode(key) {
    let record = findTableDataRecord(key);
    expandedRowKeys.value.push(key);
    let result = await getChildList({ pid: key });
    if (result && result.length > 0) {
      record.children = getDataByResult(result);
    } else {
      record.children = null;
      record.hasChild = '0';
    }
    updateTableDataRecord(key, record);
  }
  /**
   * 操作栏
   */
  function getTableAction(record) {
    return [
      {
        label: '拆分子问题',
        onClick: handleAddSub.bind(null, record),
        ifShow: () => {
          return record.pid == '0';
        }, // 子问题不允许拆分
        disabled:
          record['assinStatus'] == '1'
            ? record['receiveStatus'] == '0' ||
              record['receiveStatus'] == '1' ||
              !(userStore.getUserInfo.username == record['headCode'] || userStore.getUserInfo.username == record['createdUser'])
            : false, // 已分配且未接收，已分配且已接收的任务不可以添加子问题
      },
      {
        label: '修改',
        onClick: handleEdit.bind(null, record),
        disabled: record['assinStatus'] == '1' ? record['receiveStatus'] == '0' || record['receiveStatus'] == '1' : false, //2、已分配且未接收和已分配且已接收的任务不可修改。
      },
      {
        label: '分配',
        onClick: handleEditFp.bind(null, record),
        disabled: (record['assinStatus'] == '1' ? record['receiveStatus'] == '1' : false) || record.hasChild == '1', // 已分配且未接收和已分配且已拒绝的任务可以重新进行分配
      },
      {
        label: '接收',
        onClick: handleEditJs.bind(null, record),
        disabled:
          (record['assinStatus'] == '1' ? !(record['receiveStatus'] == '0' && userStore.getUserInfo.username == record['headCode']) : true) ||
          record.hasChild == '1', // 已分配 未接收可以显示
      },
      {
        label: '详情',
        onClick: handleDetail.bind(null, record),
      },
      {
        label: '删除',
        popConfirm: {
          title: '确定要删除吗？',
          confirm: handleDelete.bind(null, record),
        },
      },
    ];
  }
  /**
   * 下拉操作栏
   */
  function getDropDownAction(record) {
    return [];
  }
</script>

<style scoped></style>
