/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-10-15 15:32:31
 * @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 KCIMPagecontainer from '@/components/KCIMPageContainer';
import { KCIMTable } from '@/components/KCIMTable';
import { formatMoneyNumber } from '@/utils/format';
import { createFromIconfontCN } from '@ant-design/icons';
import FormItem from 'antd/es/form/FormItem';

import {
  ActionType,
  ProFormDateTimePicker,
  ProFormInstance,
  ProFormText,
} from '@ant-design/pro-components';
import {
  ModalForm,
  ProFormDependency,
  ProFormDigit,
  ProFormRadio,
  ProFormSelect,
  ProFormSwitch,
} from '@ant-design/pro-form';
import { ProColumns } from '@ant-design/pro-table';
import { Input, message, Popconfirm, Form } from 'antd';
import { useEffect, useRef, useState } from 'react';

import 'moment/locale/zh-cn';
import locale from 'antd/es/date-picker/locale/zh_CN';

import {
  addData,
  delData,
  editData,
  getSpaceCostTableData,
  importDataPost,
} from './service';

import './style.less';
import KCIMUpload from '@/components/KCIMUpload';
import { downloadTemplateReq, renameChildListToChildren } from '@/utils/tooljs';

const IconFont = createFromIconfontCN({
  scriptUrl: '',
});

export default function SpaceCostManagement() {
  const [tableDataFilterParams, set_tableDataFilterParams] = useState<
    any | undefined
  >();
  const [tableDataSearchKeywords, set_tableDataSearchKeywords] =
    useState<string>('');
  const tableRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  const [stopStat, set_stopStat] = useState(0);
  const columns: ProColumns[] = [
    {
      title: '空间名称',
      dataIndex: 'name',
    },
    {
      title: '空间编码',
      dataIndex: 'code',
    },
    {
      title: '建置成本（元）',
      dataIndex: 'cost',
      align: 'right',
    },
    {
      title: '建置容积（㎡）',
      dataIndex: 'volume',
      align: 'right',
    },
    {
      title: '折旧年限',
      dataIndex: 'depreciationYear',
      renderText(num) {
        return formatMoneyNumber(num);
      },
    },
    {
      title: '每年折旧',
      align: 'right',
      dataIndex: 'costPerYear',
      renderText(num) {
        return formatMoneyNumber(num);
      },
    },
    {
      title: '每分钟成本',
      align: 'right',
      dataIndex: 'costPerMinute',
    },
    {
      title: '停用',
      dataIndex: 'status',
      renderText(num) {
        return num ? '是' : '否';
      },
    },
    {
      title: '操作',
      key: 'option',
      width: 120,
      valueType: 'option',
      render: (_: any, record: any) => {
        return record.type == 0
          ? [
              <UpDataActBtn key={'act'} record={record} type="EDIT" />,
              <Popconfirm
                title="是否确认删除？"
                key="del"
                onConfirm={() => delTableData(record)}
              >
                <a>删除</a>
              </Popconfirm>,
              <UpDataActBtn key={'act2'} record={record} type="ADDCHILD" />,
            ]
          : [
              <UpDataActBtn key={'act'} record={record} type="EDIT" />,
              <Popconfirm
                title="是否确认删除？"
                key="del"
                onConfirm={() => delTableData(record)}
              >
                <a>删除</a>
              </Popconfirm>,
            ];
      },
    },
  ];

  const getTableData = async (params: any) => {
    let resp = await getSpaceCostTableData({ ...params, stop: stopStat });
    if (resp) {
      const data = renameChildListToChildren(resp, 'childList');
      return {
        data: data,
        success: true,
      };
    }
    return [];
  };

  const delTableData = async (record: any) => {
    const resp = await delData(record.id);
    if (resp) {
      message.success('操作成功！');
      tableRef.current?.reload();
      // message.success('操作成功!');
    }
  };

  const updateTable = async (
    formVal: any,
    type: 'EDIT' | 'ADD' | 'ADDCHILD',
  ) => {
    const result = {
      ...formVal,
    };

    if (type == 'ADD' || type == 'ADDCHILD') {
      const resp = await addData(result);
      if (resp) {
        tableRef.current?.reload();
        message.success('操作成功！');
      }
    }
    if (type == 'EDIT') {
      const resp = await editData({ ...result });
      if (resp) {
        tableRef.current?.reload();
        message.success('操作成功！');
      }
    }
    return true;
  };

  const UpDataActBtn = ({
    record,
    type,
  }: {
    record: any;
    type: 'EDIT' | 'ADD' | 'ADDCHILD';
  }) => {
    return (
      <ModalForm
        title={`${type == 'EDIT' ? '编辑' : '新增'}设备`}
        width={350}
        formRef={formRef}
        initialValues={
          type == 'EDIT'
            ? {
                ...record,
              }
            : { status: 0 }
        }
        trigger={
          type == 'EDIT' ? (
            <a key="edit">编辑</a>
          ) : (
            <a className="add">{type == 'ADD' ? '新增' : '添加'}</a>
          )
        }
        onFinish={(val) => {
          return updateTable(
            type == 'EDIT'
              ? { ...record, ...val }
              : type == 'ADDCHILD'
              ? { ...val, parentCode: record.code }
              : { ...val, parentCode: 0 },
            type,
          );
        }}
        modalProps={{ destroyOnClose: true }}
        colProps={{ span: 24 }}
        grid
      >
        <ProFormText
          name="code"
          label="空间编码："
          placeholder="请输入"
          rules={[{ required: true, message: '空间编码不能为空!' }]}
        />
        <ProFormText
          name="name"
          label="空间名称："
          placeholder="请输入"
          rules={[{ required: true, message: '空间名称不能为空!' }]}
        />
        <ProFormRadio.Group
          name="type"
          label="分类："
          options={[
            { label: '否', value: 1 },
            { label: '是', value: 0 },
          ]}
          rules={[{ required: true, message: '分类不能为空!' }]}
        />

        <ProFormDependency name={['type']}>
          {({ type }) => {
            return (
              type == 1 && (
                <>
                  <ProFormDigit
                    name="cost"
                    label="建置成本（元）："
                    placeholder="请输入"
                    rules={[{ required: true, message: '建置成本不能为空!' }]}
                  />
                  <ProFormDigit
                    name="volume"
                    label="建置容积（㎡）：："
                    placeholder="请输入"
                    rules={[{ required: true, message: '建置容积不能为空!' }]}
                  />
                  <ProFormDigit
                    name="depreciationYear"
                    label="折旧年限："
                    placeholder="请输入"
                    rules={[{ required: true, message: '折旧年限不能为空!' }]}
                  />
                  <Form.Item
                    style={{ width: 322 }}
                    label={
                      <span style={{}}>
                        <i
                          style={{
                            fontSize: 14,
                            color: '#FF4060',
                            fontWeight: 400,
                            position: 'relative',
                            paddingRight: 4,
                            paddingLeft: 4,
                          }}
                        >
                          *
                        </i>
                        停用：
                      </span>
                    }
                  >
                    <div
                      style={{
                        display: 'flex',
                        flex: 1,
                        flexDirection: 'row',
                        justifyContent: 'space-between',
                      }}
                    >
                      <ProFormRadio.Group
                        name="status"
                        noStyle
                        colProps={{ span: 10 }}
                        options={[
                          {
                            label: '否',
                            value: 0,
                          },
                          {
                            label: '是',
                            value: 1,
                          },
                        ]}
                      />
                      {/* style={{position:'relative',left:-10}}  */}
                      <ProFormDependency name={['status']}>
                        {({ status }) => {
                          // console.log({report});
                          return status ? (
                            <ProFormDateTimePicker
                              fieldProps={{ locale }}
                              name="stopTime"
                              colProps={{ span: 14 }}
                              noStyle
                            />
                          ) : null;
                        }}
                      </ProFormDependency>
                    </div>
                  </Form.Item>
                </>
              )
            );
          }}
        </ProFormDependency>
      </ModalForm>
    );
  };

  const tableDataSearchHandle = (paramName: string) => {
    set_tableDataFilterParams({
      ...tableDataFilterParams,
      [`${paramName}`]: tableDataSearchKeywords,
    });
  };

  const downloadTemplate = async () => {
    await downloadTemplateReq('/costAccount/setting/exportSpaceCost');
  };

  const importData = () => {
    return (
      <ModalForm
        width={360}
        title={`导入数据`}
        trigger={
          <a className="import" key="3">
            导入
          </a>
        }
        submitter={{
          render: (props, defaultDoms) => {
            const needBtn = defaultDoms.filter((b) => {
              return b.key != 'rest';
            });
            return [
              // <Button
              //     key="ok"
              //     onClick={auditType == '0' ? () => downloadTemplate(index) : () => { }}
              // >
              //     下载模板
              // </Button>,
              ...needBtn,
            ];
          },
        }}
        onFinish={async (values) => {
          const {
            importFile: { fileList },
          } = values;

          let formData = new FormData();
          formData.append('file', fileList[0].originFileObj);
          const resp = await importDataPost(formData);

          if (resp) {
            tableRef.current?.reload();
            return true;
          }
        }}
      >
        <FormItem name={'importFile'}>
          <KCIMUpload downloadTemplateFile={() => downloadTemplate()} />
        </FormItem>
      </ModalForm>
    );
  };

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

  return (
    <KCIMPagecontainer className="SpaceCostManagement" title={false}>
      <div className="toolBar">
        <div className="filter">
          <div className="filterItem">
            <span className="label" style={{ whiteSpace: 'nowrap' }}>
              {' '}
              空间名称：
            </span>
            <Input
              placeholder={'请输入'}
              allowClear
              autoComplete="off"
              suffix={
                <IconFont
                  type="iconsousuo"
                  style={{ color: '#99A6BF' }}
                  onClick={() => tableDataSearchHandle('name')}
                />
              }
              onChange={(e) => {
                set_tableDataSearchKeywords(e.target.value);
                if (e.target.value.length == 0) {
                  set_tableDataFilterParams({
                    ...tableDataFilterParams,
                    name: '',
                  });
                }
              }}
              onPressEnter={(e) => {
                set_tableDataFilterParams({
                  ...tableDataFilterParams,
                  name: (e.target as HTMLInputElement).value,
                });
              }}
            />
          </div>
        </div>
        <div className="btnGroup">
          <span style={{ paddingRight: 16 }}>
            <ProFormSwitch
              noStyle
              fieldProps={{
                size: 'small',
                onChange: (bool) => {
                  set_stopStat(bool ? 1 : 0);
                  tableRef.current?.reload();
                },
              }}
            />{' '}
            显示停用项目
          </span>
          {importData()}
          <UpDataActBtn record type="ADD" />
        </div>
      </div>

      <div style={{ marginTop: 16 }}>
        <KCIMTable
          pagination={false}
          scroll={{ y: `calc(100vh - 233px)` }}
          columns={columns as ProColumns[]}
          actionRef={tableRef}
          rowKey="id"
          params={tableDataFilterParams}
          request={(params) => getTableData(params)}
        />
      </div>
    </KCIMPagecontainer>
  );
}
