/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2023-10-30 14:04:24
 * @FilePath: /KC-MiddlePlatform/src/pages/platform/setting/pubDicTypeMana/index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import { ModalForm, ProFormText } from '@ant-design/pro-form';

import { Tabs, Popconfirm } from 'antd';
import { useEffect, useRef, useState } from 'react';

import { addData, delData, editData, getData, getTabs } from './service';

import './style.less';

import KCIMPagecontainer from '@/components/KCIMPageContainer';
import { KCIMTable } from '@/components/KCIMTable';

import {
  ProFormDependency,
  ProFormDigit,
  ProFormInstance,
  ProFormRadio,
  ProFormSelect,
} from '@ant-design/pro-components';
import { getTargetDic } from '@/services/auth';

export default function reportItemSet() {
  const tableRef = useRef();
  const [tabs, set_tabs] = useState<any[]>([]);

  const [currentEdit, set_currentEdit] = useState<any | undefined>(undefined);
  const [tableData, set_tableData] = useState<any[]>([]);
  const [currentTab, set_currentTab] = useState<any | undefined>(undefined);

  const columns = [
    {
      title: '报表项目名称',
      dataIndex: 'columnName',
    },
    {
      title: '报表项目代码',
      dataIndex: 'columnCode',
    },
    {
      title: '计算方式',
      dataIndex: 'computeTypeName',
    },
    {
      title: '计算来源',
      dataIndex: 'computeSourceName',
    },
    {
      title: '序号',
      dataIndex: 'sort',
    },
    {
      title: '下钻界面',
      dataIndex: 'redirectName',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: '15%',
      render: (_: any, record: { parentColumnCode: any; id: any }) => {
        const { parentColumnCode } = record;
        const delBtn = () => (
          <Popconfirm
            key={3}
            title="是否确定删除？"
            onConfirm={() => delTableData(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <a key={3}>删除</a>
          </Popconfirm>
        );
        return parentColumnCode == '0'
          ? [
              <UpDataActBtn key={1} record={record} type={'ADD'} />,
              <UpDataActBtn key={2} record={record} type={'EDIT'} />,
              delBtn(),
            ]
          : [<a key={1}>编辑</a>, delBtn()];
      },
    },
  ];

  const getTableData = async (key: any) => {
    const resp = await getData(key);
    if (resp) {
      set_tableData(resp.map((a: any) => ({ ...a, children: a.childColumns })));
      //const columns = convertToColumnsFunc(title, true);
    }
  };

  const delTableData = async (id: any) => {
    const resp = await delData(id);
    const { status } = resp;
    if (status == 200) {
      getTableData(currentTab.key);
    }
  };

  const updateTable = async (
    formVal: {
      columnName: any;
      computeType: number;
      computeSource: any;
      parentColumnCode: any;
      sort: any;
      dataType: any;
      redirect: any;
      redirectParameter: any[];
      id: any;
    },
    type: string,
  ) => {
    try {
      const result = {
        reportCode: currentTab.key,
        columnName: formVal.columnName,
        computeType: formVal.computeType,
        computeSource: formVal.computeType != 3 ? formVal.computeSource : 3,
        parentColumnCode:
          formVal.computeType == 1 ? formVal.parentColumnCode : '',
        sort: formVal.sort,
        dataType: formVal.dataType,
        redirect: formVal.redirect,
        redirectParameter: formVal.redirectParameter
          ? formVal.redirectParameter instanceof Array
            ? formVal.redirectParameter.join(',')
            : formVal.redirectParameter
          : '',
      };

      if (type == 'ADD') {
        const resp = await addData({ ...result });
        if (resp) {
          getTableData(currentTab.key);
        }
      }
      if (type == 'EDIT') {
        const resp = await editData({ ...result, id: formVal.id });
        if (resp) {
          getTableData(currentTab.key);
        }
      }
    } catch (e) {
      console.log({ e });
    }

    return true;
  };

  const UpDataActBtn = ({
    record,
    type,
  }: {
    record: any;
    type: 'ADD' | 'EDIT';
  }) => {
    const formRef = useRef<ProFormInstance<any>>();
    return (
      <ModalForm
        title={`${type == 'EDIT' ? '编辑' : record ? '添加' : '新增'}报表`}
        width={400}
        initialValues={
          type == 'EDIT'
            ? {
                ...record,
                redirectParameter: record.redirectParameter
                  ? record.redirectParameter.split(',')
                  : [],
              }
            : { computeType: 1, dataType: 1 }
        }
        trigger={
          type == 'EDIT' ? (
            <a key="edit">编辑</a>
          ) : (
            <a className="add">{record ? '添加' : '新增'}</a>
          )
        }
        onFinish={(val) => {
          set_currentEdit(undefined);
          return updateTable(
            type == 'EDIT'
              ? { ...record, ...val, id: record.id }
              : { ...val, parentColumnCode: record ? record.columnCode : '0' },
            type,
          );
        }}
        formRef={formRef}
        modalProps={{ destroyOnClose: true }}
      >
        <ProFormText
          name="columnName"
          label="报表项目名称："
          placeholder="请输入"
          rules={[{ required: true, message: '名称不能为空!' }]}
        />
        <ProFormSelect
          name="computeType"
          label="计算方式："
          options={[
            { label: '对应成本项', value: 1 },
            { label: '计算公式', value: 2 },
            { label: '合计', value: 3 },
          ]}
          rules={[{ required: true, message: '计算方式不能为空!' }]}
        />
        <ProFormDependency name={['computeType']}>
          {({ computeType }) => {
            if (computeType == 1) {
              return (
                <ProFormSelect
                  name="computeSource"
                  label="报表项目类别："
                  request={async () => {
                    const resp = await getTargetDic('REPORT_ITEM_TYPE');
                    if (resp) {
                      const { dataVoList } = resp;
                      return dataVoList.map((a: any) => {
                        if (a.defaultValue && type == 'ADD') {
                          formRef.current?.setFieldValue(
                            'computeSource',
                            a.code,
                          );
                        }
                        return { label: a.name, value: a.code };
                      });
                    }
                    return [];
                  }}
                  rules={[{ required: true, message: '报表项目类别不能为空!' }]}
                />
              );
            }
            if (computeType == 2) {
              return (
                <ProFormText
                  name="computeSource"
                  label="计算公式："
                  placeholder="请输入"
                  rules={[{ required: true, message: '名称不能为空!' }]}
                />
              );
            }
          }}
        </ProFormDependency>

        <ProFormDigit
          name="sort"
          label="序号："
          placeholder="请输入"
          rules={[{ required: true, message: '序号不能为空!' }]}
        />
        <ProFormRadio.Group
          name="dataType"
          label="数据格式："
          options={[
            { label: '数值', value: 1 },
            { label: '百分比', value: 2 },
          ]}
          rules={[{ required: true }]}
        />
        <ProFormSelect
          name="redirect"
          label="下钻界面："
          request={async () => {
            const resp = await getTargetDic('REPORT_REDIRECT_PATH');
            if (resp) {
              const { dataVoList } = resp;
              return dataVoList.map((a: any) => {
                if (a.defaultValue && type == 'ADD') {
                  formRef.current?.setFieldValue('redirect', a.code);
                }
                return { label: a.name, value: a.code };
              });
            }
            return [];
          }}
          rules={[{ required: true, message: '下钻界面不能为空!' }]}
        />
        <ProFormDependency name={['redirect']}>
          {({ redirect }) => {
            return redirect != '0' ? (
              <ProFormSelect
                name="redirectParameter"
                label="下钻参数："
                fieldProps={{ mode: 'multiple' }}
                request={async () => {
                  const resp = await getTargetDic('REPORT_REDIRECT_PARAM');
                  if (resp) {
                    const { dataVoList } = resp;
                    return dataVoList.map((a: any) => {
                      if (a.defaultValue && type == 'ADD') {
                        formRef.current?.setFieldValue(
                          'redirectParameter',
                          a.value ? a.value.split(',') : [],
                        );
                      }
                      return { label: a.name, value: a.value };
                    });
                  }
                  return [];
                }}
                rules={[{ required: true, message: '下钻参数不能为空!' }]}
              />
            ) : null;
          }}
        </ProFormDependency>
      </ModalForm>
    );
  };

  const getTabsReq = async () => {
    const resp = await getTabs();
    if (resp) {
      set_tabs(
        resp.map((a: { code: any; name: any }) => ({
          key: a.code,
          label: a.name,
        })),
      );
      set_currentTab({ key: resp[0].code, label: resp[0].name });
      getTableData(resp[0].code);
    }
  };

  const onTabChanged = (key: any) => {
    const needitem = tabs.filter((a: { key: any }) => a.key == key);
    set_currentTab(needitem[0]);
    getTableData(key);
  };

  useEffect(() => {
    getTabsReq();
  }, []);

  return (
    <KCIMPagecontainer className="reportItemSet" title={false}>
      <Tabs
        defaultActiveKey={tabs.length > 0 ? tabs[0].key : undefined}
        items={tabs}
        key={'key'}
        onChange={(key) => onTabChanged(key)}
      />
      <div className="toolBar">
        <div className="filter"></div>
        <div className="btnGroup">
          {/* <a className='copy'>复制</a> */}
          <UpDataActBtn record={undefined} type="ADD" />
        </div>
      </div>
      <div>
        <KCIMTable
          columns={columns}
          actionRef={tableRef}
          rowKey="id"
          dataSource={tableData}
        />
      </div>
    </KCIMPagecontainer>
  );
}
