import React, { useEffect, useState } from 'react';
import { Modal, Form, Button, Space, Input, Checkbox, Row, Col, Typography, Spin, InputNumber, Divider } from 'antd';

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

const WorksheetModal = (props) => {
  const { onCancel, visible, ids, report } = props;
  const [loading, setLoading] = useState(false);
  const [assets, setAssets] = useState();

  const [ form ] = Form.useForm();

  useEffect(() => {
    if (visible && (ids??[]).length>0) {
      getAssets()
    }
  }, [visible, ids])

  const getAssets = () => {
    setLoading(true)
    dispatch({
      type: 'assetmanage.listDataAssetDetails',
      payload: { 
        data: ids
      },
      callback: data => {
        setLoading(false);
        setAssets(data);
        const newFiledsValue = {}; 
        (data??[]).forEach(item => {
          newFiledsValue[`limit-${item.id}`] = 10000;
          newFiledsValue[`columns-${item.id}`] = item.columns;
        });
        form?.setFieldsValue(newFiledsValue);
      },
      error: () => {
        setLoading(false)
      }
    })
  }

  const onOk = async() => {
    try {
      const row = await form?.validateFields();

      setLoading(true);
      dispatch({
        type: 'assetmanage.saveWorkbookByType',
        payload: { 
          data: {
            name: row.name,
            type: report?.code,
            dataAssetList: (assets??[]).map(item => ({
              dataAssetId: item.id,
              metadataTableId: item.metadataId,
              limit: row[`limit-${item.id}`],
              columns: row[`columns-${item.id}`],
            }))
          }
        },
        callback: data => {
          setLoading(false);
          if (report?.code === 'SpreadJS') {
            window.open(`/data-govern/spreadjs-view?downloadurl=${encodeURIComponent(data??'')}`)
          } else {
            window.open(data);
          }

          reset();
          showMessage("success","新增成功");
          onCancel && onCancel(true);
        },
        error: () => {
          setLoading(false);
        }
      })
    } catch (errInfo) {
      console.log('Validate Failed:', errInfo);
    }
  }

  const reset = () => {
    setLoading(false);
    setAssets();
    form?.resetFields();
  }

  const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 4 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 20 },
    },
  };

  return (
    <Modal
      centered destroyOnClose
      title={`${report?.name}工作簿信息`}
      visible={ visible }
      width={ 800 }
      bodyStyle={{ padding: '15px', overflowX: 'auto', maxHeight: '80vh' }}
      onCancel={() => { 
        reset();
        onCancel && onCancel(); 
      }}
      footer={
        <Space>
          <Button onClick={() => { 
            reset();
            onCancel && onCancel(); 
          }}>取消</Button>
          <Button type="primary" onClick={onOk}>确定</Button>
        </Space>
      }
    >
      <Spin spinning={loading}>
        <Form form={form} style={{ maxHeight: 600, overflow: 'auto' }} {...formItemLayout}>
          <Form.Item
            label="名称"
            name="name"
            rules={[{ required: true, message: '请填写工作簿名称!' }]}
            style={{ marginBottom: 15 }}
          >
            <Input />
          </Form.Item>
          {
            (assets??[]).map(item => <>
              <Divider style={{ marginTop: 0, marginBottom: 15 }} />
              <Row>
                <Col span={(report?.code==='SpreadJS')?12:24}>
                  <Form.Item label="库表" labelCol={{ span: (report?.code==='SpreadJS')?8:4 }} style={{ marginBottom: 15 }}>{item.dataAssetCnName?item.dataAssetCnName:item.dataAssetEnName}</Form.Item>
                </Col>
                <Col span={12}>
                {
                  (report?.code === 'SpreadJS') && <Form.Item
                    label="最大加载行数"
                    labelCol={{ span: 8 }}
                    name={`limit-${item.id}`}
                    rules={[{ required: true, message: '请选择最大加载行数!' }]}
                    style={{ marginBottom: 15 }}
                  >
                    <InputNumber min={0} />
                  </Form.Item>
                }
                </Col>
              </Row>
              <Form.Item
                label="字段"
                name={`columns-${item.id}`}
                rules={[{ required: true, message: '请选择字段!' }]}
                style={{ marginBottom: 15 }}
              >
                <ColumnsItem data={item?.columns} /> 
              </Form.Item>
            </>)
          }
        </Form>
      </Spin>
    </Modal>
  );
} 

export default WorksheetModal;

const ColumnsItem = ({ value, onChange, data }) => {
  return (
    <Checkbox.Group 
      onChange={(checkedValue) => {
        if ((checkedValue??[]).length === 0) {
          onChange([])
        } else {
          onChange((data??[]).filter(item => checkedValue.includes(item.metadataColumnId)))
        }
      }}
      value={(value??[]).map(item => item.metadataColumnId)}
      style={{ width: '100%', overflow: 'hidden' }}
    >
      <Row>
      {
        data?.map((item, index) => <Col key={index} span={8}>
          <Checkbox
            value={item.metadataColumnId}
            style={{
              lineHeight: '32px',
            }}
          >
            <Typography.Text style={{ width: 180 }} ellipsis>{item.name}</Typography.Text>
          </Checkbox>
        </Col>)
      }
      </Row>
    </Checkbox.Group>
  )
}