<template>
  <PageWrapper dense contentFullHeight fixedHeight contentClass="flex">
    <BasicTree
      class="w-1/4 m-4 mr-0 overflow-hidden bg-white xl:w-1/5"
      v-if="treeVisible"
      ref="asyncExpandTreeRef"
      :title="treeTitle"
      toolbar
      treeWrapperClassName="h-[calc(100%-35px)] overflow-auto"
      loadData
      :actionList="actionList"
      :clickRowToExpand="false"
      :treeData="treeData"
      :fieldNames="{ key: 'value', title: 'label' }"
      :defaultExpandAll="true"
      @select="handleSelect"
    />
    <BasicTable @register="registerTable" class="flex-1">
      <template #toolbar>
        <div v-for="(item, index) in btnArr" :key="index">
          <a-button :type="item.class" @click="handleClickForm(item.prop)">{{
            item.label
          }}</a-button>
        </div>
      </template>
    </BasicTable>
    <CallModal @success="submitsuccess" @register="registerModal" />
    <a-modal
      width="100%"
      wrap-class-name="full-modal"
      v-model:open="previewOpen"
      title="流程发起"
      :destroyOnClose="true"
    >
      <template #footer> </template>
      <CreateFlow
        ref="posRef"
        :code="flowCode"
        @closeModel="closeMolder"
        :flowFormData="flowFormData"
        :isUpdate="isUpdate"
      />
    </a-modal>
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { onMounted, ref, nextTick, unref, h } from 'vue';
  import { useRoute } from 'vue-router';
  import { BasicTable, useTable, BasicColumn, FormSchema } from '@/components/Table';
  import { BasicTree, TreeItem, TreeActionItem, TreeActionType } from '@/components/Tree';
  import { getFormsDesignData, getFormsPageData, delFormsData } from '@/api/formrender/index';
  import { getOutKeyList } from '@/api/formdesign/index';
  import { PageWrapper } from '@/components/Page';
  import { cloneDeep } from 'lodash-es';
  import { IFormConfig } from '../../form-design/typings/v-form-component';
  import { useModal } from '@/components/Modal';
  import { useMessage } from '@/hooks/web/useMessage';
  import CallModal from './CallModal.vue';
  import CreateFlow from './CreateFlow.vue';

  const { createConfirm, createMessage } = useMessage();
  const route = useRoute();
  const btnArr: any = [
    { label: '新增', prop: 'Add', class: 'primary' },
    { label: '编辑', prop: 'Edit', class: 'success' },
    { label: '删除', prop: 'Delete', class: 'error' },
    { label: '详情', prop: 'Details', class: 'default' },
  ];
  const treeTitle: any = ref('树形');
  const treeVisible: any = ref(false);
  const paramsId: any = ref();
  const designData: any = ref();
  const searchValue: any = ref();
  const addParamsArr: any = ref([]);
  const paramsCode = route.query.code;
  const callColumns: BasicColumn[] = [];
  const searchFormSchema: FormSchema[] = ref([]);
  const btnList: any = ref([]);
  const treeData = ref<TreeItem[]>([]);
  const asyncExpandTreeRef = ref<Nullable<TreeActionType>>(null);
  const actionList: TreeActionItem[] = [];
  const previewOpen = ref(false); //是否打开流程发起弹窗
  const flowCode = ref(''); //流程code
  const flowFormData = ref({}); //编辑时表单的数据
  const isUpdate = ref(false); //是否是编辑
  if (paramsCode == '数据统计') {
    searchFormSchema.value = [
      {
        field: 'typeid',
        component: 'ApiSelect',
        label: '企业类型',
        colProps: { span: 6 },
        componentProps: () => {
          return {
            // api: getLoadCaseType, // 接口
            // 接口参数
            resultField: 'result',
            labelField: 'itemName',
            valueField: 'itemDetailId',
          };
        },
      },
      {
        field: 'deal_username',
        component: 'Input',
        label: '面积（m²）',
        colProps: { span: 6 },
      },
      {
        field: '[report_start_time, report_end_time]',
        component: 'RangePicker',
        label: '成立时间',
        componentProps: {
          format: 'YYYY-MM-DD',
          placeholder: ['开始时间', '结束时间'],
        },
        colProps: { span: 8 },
      },
      {
        field: 'is_intact',
        component: 'Select',
        label: '是否纳税',
        colProps: { span: 6 },
        defaultValue: 1,
        componentProps: {
          options: [
            { label: '未判读', value: 0, key: '0' },
            { label: '已提交', value: 1, key: '1' },
            { label: '已关闭', value: 99, key: '99' },
            { label: '全部', value: null, key: '' },
          ],
        },
      },
    ];
  } else if (paramsCode == '数据审核') {
    searchFormSchema.value = [
      {
        field: 'typeid',
        component: 'ApiSelect',
        label: '企业类型',
        colProps: { span: 6 },
        componentProps: () => {
          return {
            // api: getLoadCaseType, // 接口
            // 接口参数
            resultField: 'result',
            labelField: 'itemName',
            valueField: 'itemDetailId',
          };
        },
      },
      {
        field: 'deal_username',
        component: 'Input',
        label: '面积（m²）',
        colProps: { span: 6 },
      },
      {
        field: '[report_start_time, report_end_time]',
        component: 'RangePicker',
        label: '成立时间',
        componentProps: {
          format: 'YYYY-MM-DD',
          placeholder: ['开始时间', '结束时间'],
        },
        colProps: { span: 8 },
      },
      {
        field: 'is_intact',
        component: 'Select',
        label: '是否已审核',
        colProps: { span: 6 },
        defaultValue: 1,
        componentProps: {
          options: [
            { label: '未判读', value: 0, key: '0' },
            { label: '已提交', value: 1, key: '1' },
            { label: '已关闭', value: 99, key: '99' },
            { label: '全部', value: null, key: '' },
          ],
        },
      },
    ];
  }
  const [registerModal, { openModal }] = useModal();
  const [registerTable, { reload, setColumns, getSelectRows, clearSelectedRowKeys }] = useTable({
    title: '表单列表',
    api: getFormsPageData,
    // rowKey: 'f_Id',
    columns: callColumns,
    formConfig: {
      labelWidth: 120,
      showAdvancedButton: false,
      schemas: searchFormSchema,
    },
    rowSelection: {
      type: 'radio',
    },
    useSearchForm: true,
    showTableSetting: true,
    bordered: true,
    beforeFetch: (data) => {
      // 接口请求前 参数处理
      var temp = {
        id: paramsId.value,
        paginationInputDto: {
          page: data.page,
          rows: data.limit,
          keyWord: data.key,
        },
        queryJson: searchValue.value,
      };
      return temp;
    },
    afterFetch: () => {
      const rel = designData.value;
      let arr: any = [];
      if (rel.primaryKey) {
        rel.db.forEach((val) => {
          let params = {
            dbCode: rel.dbCode,
            tableNames: val.name,
          };
          let chlidKey: any = ref();
          if (val.type === 'chlid') {
            getOutKeyList(params).then((res: Recordable) => {
              if (res[0]) {
                res[0].db_codecolumnsList.forEach((item) => {
                  if (item.isPrimaryKey == 1) {
                    chlidKey.value = item.dbColumnName;
                  }
                });
              }
            });
          }
          rel.formInfo.schemas.forEach((item) => {
            if (
              item.componentProps.dataTable == val.name &&
              rel.primaryKey == item.componentProps.fieldName
            ) {
              arr.push({
                type: val.type,
                field: item.field,
              });
            }
            if (
              val.type == 'chlid' &&
              val.name == item.componentProps.dataTable &&
              chlidKey.value == item.componentProps.fieldName
            ) {
              arr.push({
                type: val.type,
                field: item.field,
              });
            }
          });
        });
      }
      addParamsArr.value = [...new Set(arr)];
    },
    handleSearchInfoFn(info) {
      return info;
    },
  });

  const formConfig = ref<IFormConfig>({
    // 表单配置
    schemas: [],
    layout: 'horizontal',
    labelLayout: 'flex',
    labelWidth: 100,
    labelCol: {},
    wrapperCol: {},
    currentItem: {
      component: '',
      componentProps: {},
    },
    activeKey: 1,
    status: 'Add',
  });

  const handleClickForm = (status) => {
    const config = cloneDeep(formConfig.value);
    const rows = getSelectRows();
    const query: any = ref({
      id: paramsId.value,
      key: designData.value.primaryKey,
      // key: 'f_id',
      keyValue: null,
    });
    const str: any = ref(addParamsArr.value[0].field);
    // const str: any = ref('_input_guid_43');
    addParamsArr.value.forEach((item) => {
      if (item.type == 'main') {
        str.value = item.field;
      }
    });

    if (rows.length > 0) {
      query.value.keyValue = rows[0][str.value];
    }
    switch (status) {
      case 'Add':
        console.log(btnList.valueField);
        btnList.value.forEach((element) => {
          if (element.prop === 'Add' && element.isWFlow) {
            flowCode.value = element.wFlowCode;
          }
        });
        if (flowCode.value == '') {
          openModal(true, {
            isDetail: false,
            isUpdate: false,
            tab: config.schemas,
            query: query.value,
            addParams: addParamsArr.value,
            btnList: btnList.value,
          });
        } else {
          flowFormData.value = {};
          previewOpen.value = true;
          isUpdate.value = false;
        }

        break;
      case 'Edit':
        if (rows.length == 0) {
          return createMessage.warn('请选择一条数据进行编辑');
        }
        btnList.value.forEach((element) => {
          if (element.prop === 'Add' && element.isWFlow) {
            flowCode.value = element.wFlowCode;
          }
        });
        if (flowCode.value == '') {
          openModal(true, {
            isDetail: false,
            isUpdate: true,
            tab: config.schemas,
            record: rows[0],
            query: query.value,
            btnList: btnList.value,
          });
        } else {
          previewOpen.value = true;
          flowFormData.value = rows[0];
          isUpdate.value = true;
        }
        break;
      case 'Delete':
        if (rows.length == 0) {
          return createMessage.warn('请选择一条数据进行删除');
        }
        createConfirm({
          iconType: 'info',
          title: '删除',
          content: '确定要删除该条数据？',
          onOk: async () => {
            delFormsData(query.value).then((res) => {
              if (res) {
                createMessage.success('删除成功', 2);
                setTimeout(() => {
                  clearSelectedRowKeys();
                  reload();
                }, 100);
              } else {
                createMessage.error('删除失败', 2);
              }
            });
          },
        });
        break;
      case 'Details':
        if (rows.length == 0) {
          return createMessage.warn('请选择一条数据查看详情');
        }
        openModal(true, {
          isDetail: true,
          isUpdate: false,
          tab: config.schemas,
          record: rows[0],
          query: query.value,
          btnList: btnList.value,
        });
        break;
      case 'Import':
        break;
      case 'Export':
        break;
      default:
        break;
    }
  };
  function handleSelect(selectedKeys: any, selected: any) {
    const rel = selected.node.dataRef;
    const obj: any = {};
    obj[rel.key] = rel.value;
    searchValue.value = JSON.stringify(obj);
    reload();
  }

  function getPublicForm() {
    let params = {
      code: paramsCode,
    };
    getFormsDesignData(params).then((res: Recordable) => {
      let columnObj = JSON.parse(res.entity.scheme);
      console.log(columnObj);
      let formObj = JSON.parse(res.formScheme.scheme);
      paramsId.value = res.formScheme.id;
      btnList.value = columnObj.table.btns;
      if (columnObj.table.columns) {
        columnObj.table.columns.forEach((item) => {
          callColumns.push({
            title: item.label,
            dataIndex: item.key,
          });
        });
      }
      callColumns.forEach((item) => {
        formObj.formInfo.schemas.forEach((val) => {
          if (item.dataIndex == val.field && val.componentProps.options) {
            item.customRender = ({ record }) => {
              const text: any = val.componentProps.options.filter(
                (price) => price.value == record[val.field],
              );
              if (text[0]) {
                return h(() => text[0].label);
              }
            };
          }
        });
      });
      setColumns(callColumns);
      reload();
      if (columnObj.left.options.length > 0) {
        treeData.value = columnObj.left.options;
        treeTitle.value = columnObj.left.title;
        treeVisible.value = true;
      } else {
        treeVisible.value = false;
      }
      designData.value = formObj;
      // 展开全部
      nextTick(() => {
        unref(asyncExpandTreeRef)?.expandAll(true);
      });
      formConfig.value.schemas = formObj.formInfo.schemas;
    });
  }
  //弹窗确定后返回调用
  function submitsuccess() {
    reload();
  }
  function closeMolder() {
    previewOpen.value = false;
    submitsuccess();
  }

  onMounted(() => {
    getPublicForm();
  });
</script>
<style lang="less">
  .full-modal {
    .ant-modal {
      max-width: 100%;
      top: 0;
    }

    .ant-modal-content {
      height: calc(100vh);
    }

    .ant-modal-body {
      height: 85%;
    }
  }
</style>
