import React, { useEffect, useState, useRef } from 'react';
import {
  ProForm,
  ProFormDigit,
  ProFormText,
  ProFormRadio,
  ProFormSelect,
  ProFormCascader,
  ProFormTextArea,
  EditableProTable,
  ActionType
} from '@ant-design/pro-components';
import { Form, Modal, Input, TimePicker } from 'antd';
import { useIntl, FormattedMessage } from '@umijs/max';
import { getMerchantSelect, getSiteTypeSelect } from '@/services/merchant/index'



const UserForm: React.FC = (props: any) => {
  const actionRef = useRef<ActionType>();


  const [form] = Form.useForm();

  const { values } = props;

  const [defaultData, setDefaultData] = useState<readonly any[]>([])
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>(() =>
    defaultData.map((item) => item.id),
  );


  const columns = [
    {
      title: '开始时间',
      dataIndex: 'startTime',
      valueType: 'time',
      fieldProps: {
        minuteStep: 30,
        secondStep: 60,
      },
      // render: (_) => {
      //   console.log(_);
        
      //   return <TimePicker  minuteStep={30} secondStep={60} />
      // }
    },
    {
      title: '结束时间',
      dataIndex: 'endTime',
      // fieldProps: {
      //   minuteStep: 30,
      //   secondStep: 60,
      // },
      // render: (_) => {
      //   return <TimePicker minuteStep={30} secondStep={60} />
      // }
      valueType: 'time',
    },
    {
      title: '模板类型',
      dataIndex: 'type',
      valueType: 'select',
      fieldProps: {
        options: [
          {
            label: '尖',
            value: 1,
          },
          {
            label: '峰',
            value: 2,
          },
          {
            label: '平',
            value: 3,
          },
          {
            label: '谷',
            value: 4,
          },
        ],
      },
    },
    {
      title: '操作',
      valueType: 'option',
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            action?.startEditable?.(record.id);
          }}
        >
          编辑
        </a>,
        <a
          key="delete"
          onClick={() => {
            setDefaultData(defaultData.filter((item) => item.id !== record.id));
            actionRef.current.reload();
          }}
        >
          删除
        </a>,
      ],
    },
  ];

  useEffect(() => {
    if (values.priceTemplateSegmentList) {
      setDefaultData(values.priceTemplateSegmentList)
    }
    form.resetFields();
    form.setFieldsValue(values);
  }, [form, props]);



  const intl = useIntl();
  const handleOk = () => {
    form.submit();
  };
  const handleCancel = () => {
    props.onCancel();
  };
  const handleFinish = async (data: any) => {
    let values = JSON.parse(JSON.stringify(data))
    if(values.piFu || values.piDi){
      delete values.piFu
      delete values.piDi
    }
    if (values.priceTemplateSegmentAddParamsList) {
      values.priceTemplateSegmentAddParamsList.map((i) => {
        if (i.id.includes('AAA')) {
          delete i.id
        }
      })
    } else {
      values.priceTemplateSegmentAddParamsList = defaultData
    }
    if (values.id) {
      values.priceTemplateSegmentUpdateParams = values.priceTemplateSegmentAddParamsList
    }
    props.onSubmit(values);
  };

  return (
    <Modal
      width={800}
      title={'价格模板信息'}
      open={props.open}
      forceRender
      destroyOnClose
      onOk={handleOk}
      onCancel={handleCancel}



    >
      <ProForm
        form={form}
        grid={true}
        submitter={false}
        layout="horizontal"
        initialValues={{
          status: 1,
          parkCostInfo: "充电停车免费"
        }}
        onFinish={handleFinish}>
        <ProFormDigit
          name="id"
          label={'ID'}
          disabled
          hidden={true}
        />

        <ProForm.Group>
          <ProFormSelect
            name="merchantId"
            label={'选择商户'}
            colProps={{ md: 8, xl: 8 }}
            placeholder="请选择商户"
            rules={[{ required: true, message: '请选择' }]}
            fieldProps={
              {
                fieldNames: {
                  label: 'label',
                  value: 'id'
                },
              }
            }
            request={async () => {
              let { data } = await getMerchantSelect()
              return data
            }}
          />
        </ProForm.Group>


        <ProForm.Group>
          <ProFormText
            name="templateName"
            label={'模板名字'}
            colProps={{ md: 12, xl: 12 }}
            placeholder="请输入模板名字"
            rules={[{ required: true, message: '请输入' }]}
          />
        </ProForm.Group>
        <ProForm.Group>

          <ProFormDigit
            name="piDi"
            label={'批量输入电费'}
            colProps={{ md: 12, xl: 12 }}
            placeholder="请输入电费"
            rules={[{ required: true, message: '请输入' }]}
            fieldProps={{
              onChange: (e) => {
                form.setFieldsValue({
                  tipElectricityRate: e,
                  peakElectricityRate: e,
                  flatElectricityRate: e,
                  valleyElectricityRate: e,
                });
              }
            }}
          />
          <ProFormDigit
            name="piFu"
            label={'批量输入服务费'}
            colProps={{ md: 12, xl: 12 }}
            placeholder="请输入服务费"
            rules={[{ required: true, message: '请输入' }]}
            fieldProps={{
              onChange: (e) => {
                form.setFieldsValue({
                  tipServiceFeeRate: e,
                  peakServiceFeeRate: e,
                  flatServiceFeeRate: e,
                  valleyServiceFeeRate: e,
                });
              }
            }}
          />

          <ProFormDigit
            name="tipElectricityRate"
            label={'尖电费'}
            colProps={{ md: 12, xl: 12 }}
            placeholder="请输入尖电费"
            rules={[{ required: true, message: '请输入' }]}
          />
          <ProFormDigit
            name="tipServiceFeeRate"
            label={'尖服务费'}
            colProps={{ md: 8, xl: 8 }}
            placeholder="请输入尖服务费"
            rules={[{ required: true, message: '请输入' }]}
          />
          <ProFormDigit
            name="peakElectricityRate"
            label={'峰电费'}
            colProps={{ md: 12, xl: 12 }}
            placeholder="请输入峰电费"
            rules={[{ required: true, message: '请输入' }]}
          />
          <ProFormDigit
            name="peakServiceFeeRate"
            label={'峰服务费'}
            colProps={{ md: 12, xl: 12 }}
            placeholder="请输入峰服务费"
            rules={[{ required: true, message: '请输入' }]}
          />
          <ProFormDigit
            name="flatElectricityRate"
            label={'平电费'}
            colProps={{ md: 12, xl: 12 }}
            placeholder="请输入平电费"
            rules={[{ required: true, message: '请输入' }]}
          />
          <ProFormDigit
            name="flatServiceFeeRate"
            label={'平服务费'}
            colProps={{ md: 12, xl: 12 }}
            placeholder="请输入平服务费"
            rules={[{ required: true, message: '请输入' }]}
          />
          <ProFormDigit
            name="valleyElectricityRate"
            label={'谷电费'}
            colProps={{ md: 12, xl: 12 }}
            placeholder="请输入谷电费"
            rules={[{ required: true, message: '请输入' }]}
          />
          <ProFormDigit
            name="valleyServiceFeeRate"
            label={'谷服务费'}
            colProps={{ md: 12, xl: 12 }}
            placeholder="请输入谷服务费"
            rules={[{ required: true, message: '请输入' }]}
          />
        </ProForm.Group>
        <ProForm.Group>
          <ProFormText
            name="parkCostInfo"
            label={'停车收费说明'}
            colProps={{ md: 12, xl: 12 }}
            placeholder="请输入停车收费说明"
            rules={[{ required: true, message: '请输入' }]}
          />
          <ProFormText
            name="occupyCostInfo"
            label={'占用收费说明'}
            colProps={{ md: 12, xl: 12 }}
            placeholder="请输入占用收费说明"
          />
        </ProForm.Group>
        <ProFormRadio.Group
          rules={[{ required: true, message: '请输入' }]}
          name="status"
          options={[
            {
              label: '启用',
              value: 1,
            },
            {
              label: '禁用',
              value: 2,
            },
          ]}
          label={'状态'}
          colProps={{ md: 12, xl: 12 }}
        />
        <ProForm.Item
          label="价格模板"
          name="priceTemplateSegmentAddParamsList"
          trigger="onValuesChange"
        >
          <EditableProTable
            rowKey="id"
            toolBarRender={false}
            columns={columns}
            actionRef={actionRef}
            recordCreatorProps={{
              newRecordType: 'dataSource',
              position: 'top',
              record: () => ({
                id: 'AAA' + Date.now(),
              }),
            }}
            value={defaultData}
            onChange={setDefaultData}
            editable={{
              type: 'multiple',
              editableKeys,
              onChange: setEditableRowKeys,
              actionRender: (row, _, dom) => {
                return [dom.delete];
              },
            }}
          />
        </ProForm.Item>
      </ProForm>
    </Modal>
  );
};

export default UserForm;
