/*
 ** 报表的编辑、新增表单
 ** create by ChenLong on 2022/8/10
 ** 功能路径:src\pages\product\ReportsManage\ReportEditForm.js
 ** 菜单参数列表:*变量名*(变量说明,数据类型,是否必填,取值范围)
 **/
import React, { useEffect, useState, useContext } from 'react';
import {
  Form,
  Input,
  DatePicker,
  InputNumber,
  Row,
  Col,
  Button,
  message,
  Select,
  ConfigProvider,
} from 'antd';
import moment from 'moment';
import { submitReportData } from '../api/service/report';
import FileUpload from './Components/fileUpload/fileUpload';
import { reportService } from '../api';
import { isSelect, returnOptions, returnRows, returnCols } from './utils/utils';
import style from './ReportEditForm.less';

const { Option } = Select;
const { TextArea } = Input;
// 类型
const USER_ID = window?.globalConfig?.userInfo?.OID || 0;
const TEXT_ARRAY = ['文本', '标签'];
const TEXTAREA_ARRAY = ['多行文本'];
const DATE_PICKER_ARRAY = ['日期'];
const DATE_TIME_PICKER_ARRAY = ['日期时刻'];
const DATE_TYPE = ['日期', '日期时刻']; // 用来匹配是否需要转为日期对象;
const NUMBER_ARRAY = ['数值', '数值标签'];
const FILE_ARRAY = ['附件'];
// 形态对应组件

// 对应关系

/**
 * @description: 函数描述
 * @date: 2022/8/10
 * @author: ChenLong
 * @params: reportDetails 各个字段的配置列表
 *           data 与reportDetails对应的值
 */
const ReportEditForm = ({ reportDetails, reportData, onCancel, reportName, modalType }) => {
  // if (!reportData || Object.keys(reportData).length === 0) return <>未传递表单数据</>;
  const [fileAlias, setFileAlias] = useState([]); // 附件需要单独处理提交的数据
  const [form] = Form.useForm();
  const { getPrefixCls } = useContext(ConfigProvider.ConfigContext);
  const prefixCls = getPrefixCls();
  /*  const formItemLayout = {
      labelCol: {
        span: 8,
      },
      wrapperCol: {
        span: 16,
      },
    };*/
  // 数值类的后端会处理再返回,故无序处理精度问题
  const handleDate = (reportDetails, data) => {
    let _data = { ...data };
    reportDetails.forEach((item) => {
      if (DATE_TYPE.includes(item.type)) {
        _data[item.fieldAlias] = data[item.fieldAlias] ? moment(data[item.fieldAlias]) : null;
      }
    });
    return _data;
  };
  const componentMap = (config) => {
    if (DATE_TIME_PICKER_ARRAY.includes(config.type)) {
      return <DatePicker showTime readonly={config.isReadOnly} />;
    } else if (DATE_PICKER_ARRAY.includes(config.type)) {
      return <DatePicker disabled={config.isReadOnly} />;
    } else if (NUMBER_ARRAY.includes(config.type)) {
      return <InputNumber disabled={config.isReadOnly} />;
    } else if (FILE_ARRAY.includes(config.type)) {
      return <FileUpload schema={{ renderTo: 'File' }} disabled={config.isReadOnly} />;
    } else if (TEXTAREA_ARRAY.includes(config.type)) {
      let _rows = returnRows(config.configItems);
      return <TextArea rows={_rows} disabled={config.isReadOnly} />;
    } else {
      if (isSelect(config.configItems)) {
        let options = returnOptions(config.configItems);
        if (options) {
          return (
            <Select disabled={config.isReadOnly}>
              {options.map((item) => (
                <Option value={item}>{item}</Option>
              ))}
            </Select>
          );
        }
      }
      return <Input disabled={config.isReadOnly} />;
    }
  };
  const submitReportForm = () => {
    form.validateFields().then((values) => {
      let _data = values;
      let final = [];
      Object.keys(_data).forEach((key) => {
        let value = reportData[key];
        let _value = _data[key];
        if (moment.isMoment(_data[key])) {
          _value = moment(_data[key]).format('YYYY-MM-DD HH:mm:ss');
        }
        if (value !== _value) {
          if (fileAlias.includes(key)) {
            _value = _value
              ? JSON.parse(_value)
                  .reduce((final, curr) => {
                    final.push(curr.sourcePath);
                    return final;
                  }, [])
                  .join(',')
              : '';
          }
          let _finalData = {
            fieldAlias: key,
            fieldValue: _value === null ? _value : String(_value),
          };
          if (modalType === '编辑') {
            _finalData.key = reportData.key;
          }
          final.push(_finalData);
        }
      });
      if (modalType === '新增') {
        reportService
          .addReportData({
            reportName: reportName,
            userId: USER_ID,
            reportDatas: final,
          })
          .then((res) => {
            if (res.code === 0) {
              message.success('保存成功!');
              onCancel();
            } else if (res.code === -1) {
              message.error(res.msg);
            } else if (res.code === -2) {
              message.error('系统故障,请找管理员查看故障!');
            }
          });
      }
      if (modalType === '编辑') {
        submitReportData(
          {},
          {
            editDatas: final,
            reportName: reportName,
            userId: USER_ID,
          },
        ).then((res) => {
          if (res.code === 0) {
            message.success('保存成功!');
            onCancel();
          } else if (res.code === -1) {
            message.error(res.msg);
          } else if (res.code === -2) {
            message.error('系统故障,请找管理员查看故障!');
          }
        });
      }
    });
  };
  useEffect(() => {
    if (reportDetails && reportDetails.length) {
      let _fileAlias = [...fileAlias];
      reportDetails.forEach((item) => {
        if (item.type === '附件') _fileAlias.push(item.fieldAlias);
      });
      setFileAlias(_fileAlias);
    }
  }, [reportDetails]);
  useEffect(() => {
    if (reportData && Object.keys(reportData).length)
      form.setFieldsValue(handleDate(reportDetails, reportData));
  }, [reportData]);
  return (
    <div className={style.reportEditForm} style={{ position: 'relative' }}>
      <div>
        <Form form={form}>
          <Row style={{ overflowY: 'scroll', maxHeight: 'calc(100vh - 300px)' }}>
            {reportDetails &&
              reportDetails
                .filter((config) => {
                  if (modalType === '新增' && config.isReadOnly) return false;
                  return config;
                })
                .map((config) => {
                  // return <Col span={returnCols(config.configItems) * 8} key={config.fieldAlias}>
                  return (
                    <div
                      style={{ width: `${returnCols(config.configItems) * 33.3}%` }}
                      key={config.fieldAlias}
                    >
                      <Form.Item
                        label={config.fieldAlias}
                        name={config.fieldAlias}
                        rules={[
                          {
                            required: config.isRequired,
                            message: `${config.fieldAlias}必填`,
                          },
                        ]}
                      >
                        {componentMap(config)}
                      </Form.Item>
                    </div>
                  );
                })}
          </Row>
          <Row>
            <Col span={24} style={{ textAlign: 'right' }}>
              {/*<Form.Item style={{textAlign:'right'}}>*/}
              <Button
                style={{ position: 'sticky', bottom: 0 }}
                type={'primary'}
                onClick={submitReportForm}
              >
                提交
              </Button>
              {/*</Form.Item>*/}
            </Col>
          </Row>
        </Form>
      </div>
    </div>
  );
};
export default ReportEditForm;