/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-10-15 15:31: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,
  getEquipTableData,
  importDataPost,
} from './service';

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

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

export default function EquipmentCostManagement() {
  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: 'code',
      width: 90,
    },
    {
      title: '项目名称',
      dataIndex: 'name',
    },
    {
      title: '设备型号',
      dataIndex: 'type',
    },
    {
      title: '折旧年限',
      dataIndex: 'depreciationYear',
    },
    {
      title: '采购价格（元）',
      dataIndex: 'price',
      align: 'right',
      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: 90,
      valueType: 'option',
      render: (_: any, record: any) => {
        return [
          <UpDataActBtn key={'act'} record={record} type="EDIT" />,
          <Popconfirm
            title="是否确认删除？"
            key="del"
            onConfirm={() => delTableData(record)}
          >
            <a>删除</a>
          </Popconfirm>,
        ];
      },
    },
  ];

  const getTableData = async (params: any) => {
    const resp = await getEquipTableData({ ...params, stop: stopStat });
    if (resp) {
      return {
        data: resp.list,
        success: true,
        total: resp.totalCount,
        pageSize: resp.pageSize,
        totalPage: resp.totalPage,
      };
    }
    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') => {
    const result = {
      ...formVal,
    };

    if (type == 'ADD') {
      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';
  }) => {
    return (
      <ModalForm
        title={`${type == 'EDIT' ? '编辑' : '新增'}设备`}
        width={350}
        formRef={formRef}
        initialValues={
          type == 'EDIT'
            ? {
                ...record,
              }
            : { status: 0 }
        }
        trigger={
          type == 'EDIT' ? (
            <a key="edit">编辑</a>
          ) : (
            <span className="add">新增</span>
          )
        }
        onFinish={(val) => {
          return updateTable(
            type == 'EDIT' ? { ...record, ...val } : { ...val },
            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: '设备名称不能为空!' }]}
        />
        <ProFormText name="type" label="设备型号：" placeholder="请输入" />
        <ProFormDigit
          name="price"
          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 }}
                    placeholder="请选择停用时间"
                    name="stopTime"
                    rules={[{ required: true, message: '时间不能为空!' }]}
                    colProps={{ span: 14 }}
                    noStyle
                  />
                ) : null;
              }}
            </ProFormDependency>
          </div>
        </Form.Item>
      </ModalForm>
    );
  };

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

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

  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="EquipmentCostManagement" 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
          scroll={{ y: `calc(100vh - 233px)` }}
          columns={columns as ProColumns[]}
          actionRef={tableRef}
          rowKey="id"
          params={tableDataFilterParams}
          request={(params) => getTableData(params)}
        />
      </div>
    </KCIMPagecontainer>
  );
}
