import React, { useEffect, useState, useMemo } from 'react';
import { Modal, Form, Input, Space, Button, Radio, Select } from 'antd';

import { dispatch } from '../../../../model';
import { showMessage } from '../../../../util';

// const resourceTypes = [
//   // { key: 'innerSource', name: '内部资源' },
//   // { key: 'outerSource', name: '外部资源' },
//   { key: 'dataAsset', name: '资产' },
//   { key: 'custom', name: '自定义' },
// ]

const CodeInput = ({ value = '', onChange, restrict = false, action }) => {

  const onCodeChange = (e) => {
    if (!restrict || (
      restrict&&(e.target.value===''||/^[A-Z]+$/.test(e.target.value))
    )) {
      onChange?.(e.target.value);
    }
  }

  return <Input 
    placeholder="请输入编号(只允许输入大写英文字母,并且最多3个)" 
    disabled={action!=='add'} 
    maxLength={restrict?3:null} 
    value={value}
    onChange={onCodeChange}
  />
}

const UpdateDirectoryModal = (props) => {

  const { visible, onCancel, dirId, action } = props;

  const [ form ] = Form.useForm();
  const [ dir, setDir ] = useState(null);
  const [ confirmLoading, setConfirmLoading ] = useState(false);
  const [ isThemeAdd, setIsThemeAdd ] = useState(false);

  useEffect(() => {

    if (visible) {
      setDir(null);
      form.resetFields();

      if (action === 'add') {
        form.setFieldsValue({ resourceType: 'dataAsset' });
      }
     
      if ((dirId||'')!=='') {
        getDirectory();
      }
    }

    //eslint-disable-next-line react-hooks/exhaustive-deps
  }, [ visible ])

  const codeRestrict = useMemo(() => {
    if (action === 'add') {
      if (isThemeAdd) return true;

      return (dir && dir.level === 1) ? true : false;
    } else {
      return (dir && dir.level <= 2) ? true : false;
    }

    return false;
  }, [action, dir, isThemeAdd])

  const getDirectory = () => {
    setDir(null);
    dispatch({
      type: 'assetmanage.getDirectoryById',
      payload: { 
        dirId
      },
      callback: data => {
        setDir(data);

        if (action !== 'add') {
          form.setFieldsValue({ code: data?.code, name: data?.name||'', desc: data?.desc||'', remarks: data?.remarks||'' });
        }
      }
    })
  }

  const onOk = async () => {
    try {
      const row = await form.validateFields();
      
      setConfirmLoading(true);
      
      let payload = {
        data: { 
          code: row.code,
          name: row.name,
          desc: row.desc,
          remarks: row.remarks,
          resourceType: 'dataAsset',
        }
      };

      if (action === 'add') {
        if (row.type === 'directory') {

          if (dir === null) {
            showMessage('warn', '资产目录的目录节点信息正在加载中...');
            return;
          }
          
          payload = { ...payload, params: {
            parentPath: dir.path||'' 
          }};
        } else {
          payload.data.resourceType = 'dataAsset';
        }
      } else {

        if (dir === null) {
          showMessage('warn', '资产目录的目录节点信息正在加载中...');
          return;
        }

        payload.data = { ...payload.data, ...{ order: dir.order, id: dirId } };
        if (dir.level === 3) {
          payload.data = { ...payload.data, code: dir.code };
        }

        const parentPath = dir.path.substring(0, dir.path.lastIndexOf("/"));;
        payload = { ...payload, params: {
          parentPath
        }};
      }

      dispatch({
        type: 'assetmanage.addOrUpdateDirectory',
        payload: payload,
        callback: data => {
          setConfirmLoading(false);
          reset();
          onCancel && onCancel(true, data?.id||'');
        },
        error: () => {
          setConfirmLoading(false);
        }
      })

    } catch (errInfo) {
      console.log('Validate Failed:', errInfo);
    }
  }

  const reset = () => {
    setIsThemeAdd(false);
    setDir(undefined);
    form.resetFields();
  }

  const onReset = () => {
    if(action === 'add') {
      setIsThemeAdd(false);
      form.resetFields();
    } else {
      if (dir === null) {
        showMessage('warn', '资产目录的目录节点信息正在加载中...');
        return;
      }

      form.setFieldsValue({ code: dir?.code, name: dir?.name||'', desc: dir?.desc||'', remarks: dir?.remarks||'' });
    }
  }

  const onValuesChange = (changedValues, allValues) => {
    if (action==='add') {
      if (changedValues.type === 'theme') {
        setIsThemeAdd(true); 
        // if (allValues.code?.length > 3 || !(/^[A-Z]+$/.test(allValues.code))) {
        //   form.setFieldsValue({ code: '' });
        // }
      } else if (changedValues.type === 'directory') {
        setIsThemeAdd(false);
      }
    }
  }

  const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 5 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 17 },
    },
  };

  return (
    <Modal
      forceRender
      title={'资产目录的目录信息'}
      visible={visible}
      width={600}
      onCancel={() => { 
        reset();
        onCancel && onCancel(); 
      }}
      footer={
        <Space>
          <Button type="primary" onClick={onOk} loading={confirmLoading}>提交</Button>
          <Button onClick={onReset} >重置</Button>
          <Button onClick={() => {
            reset();
            onCancel && onCancel();
          }}>返回</Button>
        </Space>
      }
    >
      <Form {...formItemLayout} form={form} onValuesChange={onValuesChange}>
        {
          action==='add' && <Form.Item 
            label="类型"
            name="type"
            rules={[{ required: true, message: '必填项' }]}
          >
            <Radio.Group>
              <Radio value='theme'>栏目</Radio>
              <Radio value='directory' disabled={ !dirId }>目录</Radio>
            </Radio.Group>
          </Form.Item>
        }
        {
          codeRestrict && <Form.Item 
            label="编号"
            name="code"
            rules={[{ required: true, message: '必填项' }]}
          >
            <CodeInput restrict={codeRestrict} action={action} />
          </Form.Item>
        }
        <Form.Item 
          label="名称"
          name="name"
          rules={[{ required: true, message: '必填项' }]}
        >
          <Input placeholder="请输入名称" />
        </Form.Item>
        {
          action !== 'add' && (
            <Form.Item
              label="路径"
              name="path"
            >
              <span>{ dir ? (dir.path||''):'' }</span>
            </Form.Item>
          )
        }
        <Form.Item 
          label="描述"
          name="desc"
        >
          <Input.TextArea placeholder="请输入描述" autoSize={{ minRows: 4, maxRows: 4 }} />
        </Form.Item>
        <Form.Item 
          label="备注"
          name="remarks"
        >
          <Input.TextArea placeholder="请输入备注" autoSize={{ minRows: 4, maxRows: 4 }} />
        </Form.Item>
      </Form>
    </Modal>
  );
}

export default UpdateDirectoryModal;