<template>
  <PageWrapper dense fixedHeight contentFullHeight contentClass="flex">
    <div class="w-1/5 xl:w-1/5 mr-2">
      <BasicTree
        v-if="treeData"
        title="工厂结构"
        toolbar
        search
        :defaultExpandAll="true"
        :clickRowToExpand="false"
        :treeData="treeData"
        :fieldNames="{ key: 'value', title: 'label' }"
        @select="handleSelect"
      >
        <template #title="item">&nbsp;&nbsp;{{ item.label }}</template>
      </BasicTree>
    </div>
    <div class="w-4/5 xl:w-4/5">
      <BasicTable
        @register="registerTable"
        :row-selection="{ selectedRowKeys: selectedKeys, onChange: onSelectChange }"
      >
        <template #toolbar>
          <template v-for="button in tableButtonConfig" :key="button.code">
            <a-button v-if="button.isDefault" type="primary" @click="buttonClick(button.code)">
              <template #icon>
                <Icon :icon="button.icon" />
              </template>
              {{ button.name }}
            </a-button>
            <a-button v-else type="primary">
              <template #icon>
                <Icon :icon="button.icon" />
              </template>
              {{ button.name }}
            </a-button>
          </template>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'action'">
            <TableAction :actions="getActions(record)" />
          </template>
        </template>
      </BasicTable>
    </div>

    <PrintPreview
      v-if="printData.visible"
      :id="printData.id"
      :request-params-configs="printData.requestParamsConfigs"
      :request-body-configs="printData.requestBodyConfigs"
      :request-header-configs="printData.requestHeaderConfigs"
      @close="printData.visible = false"
    />

    <BaseFactoryModal v-else @register="registerModal" @success="handleSuccess" />
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { ref, computed, onMounted, createVNode, getCurrentInstance, reactive } from 'vue';

  import { Modal } from 'ant-design-vue';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import { BasicTable, useTable, TableAction, ActionItem } from '/@/components/Table';
  import {
    getMesBaseFactoryPage,
    deleteMesBaseFactory,
    exportMesBaseFactory,
  } from '/@/api/mes/basefactory';
  import { PageWrapper } from '/@/components/Page';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { usePermission } from '/@/hooks/web/usePermission';
  import { useRouter } from 'vue-router';

  import { getPrintConfigInfo } from '/@/api/system/generator/print';
  import PrintPreview from '/@/views/generator/print/Preview.vue';
  import { getMesBaseFactory } from '/@/api/mes/basefactory';
  import { PrintButton } from '/@/enums/printEnum';
  import { InputParamItem } from '/@/components/ApiConfig/src/interface';

  import { useModal } from '/@/components/Modal';

  import BaseFactoryModal from './components/BaseFactoryModal.vue';

  import { downloadByData } from '/@/utils/file/download';

  import { searchFormSchema, columns, columns1, columns2, columns3 } from './components/config';
  import Icon from '/@/components/Icon/index';

  import { BasicTree, TreeItem } from '/@/components/Tree';

  import { apiConfigFunc } from '/@/utils/event/design';
  const { notification } = useMessage();
  const { t } = useI18n();
  defineEmits(['register']);
  const { filterColumnAuth, filterButtonAuth } = usePermission();

  const filterColumns = filterColumnAuth(columns, false);
  const filterColumns1 = filterColumnAuth(columns1, false);
  const filterColumns2 = filterColumnAuth(columns2, false);
  const filterColumns3 = filterColumnAuth(columns3, false);
  //展示在列表内的按钮
  const actionButtons = ref<string[]>(['view', 'edit', 'delete', 'startwork']);
  const buttonConfigs = computed(() => {
    const list = [
      {
        isUse: true,
        isShow: false,
        code: 'add',
        icon: 'ant-design:plus-outlined',
        isDefault: true,
        name: '新增',
      },
      {
        isUse: true,
        code: 'edit',
        icon: 'ant-design:form-outlined',
        isDefault: true,
        name: '编辑',
      },
      {
        isUse: true,
        code: 'delete',
        icon: 'ant-design:delete-outlined',
        isDefault: true,
        name: '删除',
      },
      {
        isUse: true,
        code: 'export',
        icon: 'ant-design:export-outlined',
        isDefault: true,
        name: '导出',
      },
    ];
    return filterButtonAuth(list);
  });

  const tableButtonConfig = computed(() => {
    return buttonConfigs.value?.filter((x) => !actionButtons.value.includes(x.code));
  });

  const actionButtonConfig = computed(() => {
    return buttonConfigs.value?.filter((x) => actionButtons.value.includes(x.code));
  });

  const btnEvent = { add: handleAdd, edit: handleEdit, delete: handleDelete, export: handleExport };

  const { currentRoute } = useRouter();
  const printMenuId = computed(() => currentRoute.value.meta.menuId as string);
  const formIdComputedRef = computed(() => currentRoute.value.meta.formId as string);

  const selectId = ref('');
  const factoryType = ref('0');
  const factoryTop = ref<any>({});
  const carTop = ref<any>({});
  const treeData = ref<TreeItem[]>([]);

  const selectedKeys = ref<string[]>([]);
  const selectedRowsData = ref<any[]>([]);

  const [registerModal, { openModal }] = useModal();

  // 模板打印 入参参数
  let printData: {
    visible: boolean;
    id: string;
    code: string;
    requestParamsConfigs: Array<InputParamItem>;
    requestHeaderConfigs: Array<InputParamItem>;
    requestBodyConfigs: Array<InputParamItem>;
  } = reactive({
    visible: false,
    id: '',
    code: '',
    requestParamsConfigs: [],
    requestHeaderConfigs: [],
    requestBodyConfigs: [],
  });

  const [registerTable, { reload, setColumns }] = useTable({
    title: '工厂资料列表',
    api: getMesBaseFactoryPage,
    rowKey: 'id',
    columns: filterColumns,
    formConfig: {
      rowProps: {
        gutter: 16,
      },
      schemas: searchFormSchema,
      fieldMapToTime: [
        ['createDate', ['createDateStart', 'createDateEnd'], 'YYYY-MM-DD HH:mm:ss ', true],
      ],
    },
    beforeFetch: (params) => {
      console.log('factoryType.value', factoryType.value);
      return {
        ...params,
        FormId: formIdComputedRef.value,
        PK: 'id',
        parentId: selectId.value ? selectId.value : '0',
      };
    },
    useSearchForm: true,
    showTableSetting: false,
    showLine: true,
    striped: false,
    actionColumn: {
      align: 'left',
      width: 160,
      title: '操作',
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
    customRow,
  });
  function buttonClick(code) {
    if (code.includes(PrintButton.CODE)) {
      printData.code = code;
    }
    btnEvent[code]();
  }
  function getFactoryTypeById() {
    if (!selectId.value || selectId.value == '0') {
      factoryType.value = '0';
    } else {
      console.log('treeData.====', treeData, selectId);
      if (treeData && treeData.value && treeData.value[0] && treeData.value[0].children) {
        console.log('treeData.value0====', treeData.value[0], selectId.value);
        treeData.value[0].children.forEach((element) => {
          if (element.value == selectId.value) {
            factoryType.value = '1';
            factoryTop.value = element;
          } else if (element.children) {
            element.children.forEach((element1) => {
              if (element1.value == selectId.value) {
                factoryType.value = '2';
                factoryTop.value = element;
                carTop.value = element1;
              } else if (element1.children) {
                element1.children.forEach((element2) => {
                  if (element2.value == selectId.value) {
                    factoryType.value = '3';
                    factoryTop.value = element;
                    carTop.value = element1;
                  }
                });
              }
            });
          }
        });
      }
    }

    console.log('factoryType', factoryType);
  }
  function handleAdd() {
    console.log('factoryTop', factoryTop, factoryTop.value, factoryTop.value.value);
    openModal(true, {
      isUpdate: false,
      factoryType: factoryType.value, //类型
      factoryId: factoryTop.value.value, //一级工厂id
      carId: carTop.value.value, //所属车间id
      parentId: selectId.value, //左侧选择的父id
    });
  }

  function handleEdit(record: Recordable) {
    openModal(true, {
      id: record.id,
      isUpdate: true,
      factoryType: factoryType.value, //类型
      // factoryId:factoryTop.value.value,//一级工厂id
      // parentId:selectId.value//左侧选择的父id
    });
  }

  function handleDelete(record: Recordable) {
    deleteList([record.id]);
  }

  function deleteList(ids) {
    Modal.confirm({
      title: '提示信息',
      icon: createVNode(ExclamationCircleOutlined),
      content: '是否确认删除？',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        deleteMesBaseFactory(ids).then((_) => {
          fetch();
          reload({ searchInfo: { parentId: selectId.value } });
          notification.success({
            message: 'Tip',
            description: t('删除成功！'),
          });
        });
      },
      onCancel() {},
    });
  }

  // 模板打印
  async function handleTemplateprint() {
    if (!selectedKeys.value.length) {
      notification.warning({
        message: t('提示'),
        description: t('请选择数据'),
      });
      return;
    }
    if (selectedKeys.value.length > 1) {
      notification.warning({
        message: t('提示'),
        description: t('只能选择一条数据进行操作'),
      });
      return;
    }
    let id = selectedKeys.value[0];
    try {
      const record = await getMesBaseFactory(id);
      let res = await getPrintConfigInfo(printData.code, printMenuId.value);
      if (res.enabledMark == null) {
        notification.warning({
          message: t('提示'),
          description: t('当前功能未绑定打印模板，请绑定后再进行模板打印。'),
        });
        return;
      }
      if (res.enabledMark == 0) {
        notification.warning({
          message: t('提示'),
          description: t('找不到打印模板，请联系管理员。'),
        });
        return;
      }
      printData.id = res.schemaId;
      if (res.apiConfig) {
        let json = JSON.parse(res.apiConfig);
        if (json.requestParamsConfigs && json.requestParamsConfigs.length > 0) {
          printData.requestParamsConfigs = json.requestParamsConfigs.map((ele) => {
            if (ele.config && record[ele.config] != undefined) {
              ele.value = record[ele.config];
            }
            return ele;
          });
        }
        if (json.requestHeaderConfigs && json.requestHeaderConfigs.length > 0) {
          printData.requestHeaderConfigs = json.requestHeaderConfigs.map((ele) => {
            if (ele.config && record[ele.config] != undefined) {
              ele.value = record[ele.config];
            }
            return ele;
          });
        }
        if (json.requestBodyConfigs && json.requestBodyConfigs.length > 0) {
          printData.requestBodyConfigs = json.requestBodyConfigs.map((ele) => {
            if (ele.config && record[ele.config] != undefined) {
              ele.value = record[ele.config];
            }
            return ele;
          });
        }
        printData.visible = true;
      } else {
        notification.warning({
          message: t('提示'),
          description: t('当前功能未绑定打印模板，请绑定后再进行模板打印。'),
        });
      }
    } catch (error) {}
  }

  function onSelectChange(selectedRowKeys: [], selectedRows) {
    selectedKeys.value = selectedRowKeys;
    selectedRowsData.value = selectedRows;
  }

  function customRow(record: Recordable) {
    return {
      onClick: () => {
        let selectedRowKeys = [...selectedKeys.value];
        if (selectedRowKeys.indexOf(record.id) >= 0) {
          let index = selectedRowKeys.indexOf(record.id);
          selectedRowKeys.splice(index, 1);
        } else {
          selectedRowKeys.push(record.id);
        }
        selectedKeys.value = selectedRowKeys;
      },
    };
  }

  function handleSuccess() {
    fetch();
    reload({ searchInfo: { parentId: selectId.value } });
  }

  async function handleExport() {
    const res = await exportMesBaseFactory({ isTemplate: false });
    downloadByData(
      res.data,
      '工厂资料列表.xlsx',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    );
  }

  function handleSelect(selectIds) {
    selectId.value = selectIds[0];
    getFactoryTypeById();

    setColumns(
      factoryType.value == '3'
        ? filterColumns3
        : factoryType.value == '2'
        ? filterColumns2
        : factoryType.value == '1'
        ? filterColumns1
        : filterColumns,
    );
    reload({ searchInfo: { parentId: selectId.value } });
  }

  async function fetch() {
    treeData.value = (await apiConfigFunc(
      {
        path: '/mes/getFactoryTreeList',
        method: 'GET',
        apiId: '3635526932a84052a603ad3a51cf5b27',
        apiParams: [
          { key: '1', title: 'Query Params', tableInfo: [] },
          { key: '2', title: 'Header', tableInfo: [] },
          { key: '3', title: 'Body' },
        ],
      },
      false,
    )) as unknown as TreeItem[];
  }

  onMounted(() => {
    fetch();
  });

  function getActions(record: Recordable): ActionItem[] {
    const actionsList: ActionItem[] = actionButtonConfig.value?.map((button) => {
      if (!record.workflowData?.processId) {
        return {
          icon: button?.icon,
          tooltip: button?.name,
          color: button.code === 'delete' ? 'error' : undefined,
          onClick: btnEvent[button.code].bind(null, record),
        };
      } else {
        if (button.code === 'view') {
          return {
            icon: button?.icon,
            tooltip: button?.name,
            onClick: btnEvent[button.code].bind(null, record),
          };
        } else {
          return {};
        }
      }
    });
    return actionsList;
  }
</script>
<style lang="less" scoped>
  :deep(.ant-table-selection-col) {
    width: 50px;
  }
</style>
