/*
 * Creater:     刘丹
 * CreateDate:  2023/03/28
 * PageName:    公用查询页面
 * Describe：   公共的表单组件页，之前的公共上传副本
 * 表头和表格内容走一个接口获取动态获取，表单查询条件走【01040073表头查询接口】，页面也走页面组件配置
 * */
import React, { Component } from 'react';
import {
  Input, Button, Col, message, Form, Row, DatePicker, Spin, Select, Table, Popover,
} from 'antd';
import moment from 'moment';
import { Util, dayFormat } from 'tools/index';
import store from "../../store";
import CommonPagination from 'components/pagination/index';
import PreviewJson from './components/PreviewJson.jsx';

class publicTableDynamicPage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      dialogContent: '', //预览的内容
      dialogContentType: '', // 预览默然的类型
      visiblePreview: false, // json预览是否显示
      page: 1,
      pageSize: 20,
      total: 0,
      loading: false,
      startDate: '',
      endDate: '',
      columns: [], // 列
      tableData: [], // 表格表单数据
      formData: [], //Table组件表单数据
      uploadParams: '',  //当前功能模块传参
      typeResultOBJ: {}, // 查询的接口和code
      tmpCol: {},
      buttonData: [], // 自定义配置的按钮
      scrollX: false, // 表格横向滚动
    }
  }

  componentDidMount () {
    let params = '';
    const { location, paras } = this.props;
    if (location) {
      if (location.state) {
        params = location.state?.params || '';
      }
    } else {
      if (paras) {
        params = paras?.params || '';
      } else {
        params = this.props?.params || '';
      }
    }
    if (params) {
      sessionStorage.setItem('commonTableParams', params);
    }
    const cacheParams = sessionStorage.getItem('commonTableParams');
    this.setState({
      uploadParams: params ? params : cacheParams
    }, function () {
      this.getFormSet(); // 获取表单的查询条件
    });
  }
  // 获取查询表单的配置
  getFormSet = async () => {
    const compontName = Util.getValueByUrlStr(this.state.uploadParams, 'componentName');
    // componentName:UploadNHIPH23
    const data = {
      params: [{
        compontName,
        type: 'C',
        reactCode: [compontName],
      }]
    };
    const resObj = await React.$asyncPost(this, '01040073', data);
    if (+resObj.errorCode === 0) {
      this.setState({
        formData: resObj.result?.formData,
        buttonData: resObj.result?.buttonData,
      });
      this.getFormDictData(resObj.result?.formData);//获取表单内的字典数据
      this.getTypeInfo(); // 获取走哪个接口查询表格数据
    } else {
      message.error(resObj.errorMessage)
    }
  }
  //获取功能类型配置详情
  getTypeInfo = async () => {
    let data = {
      params: [{
        modularType: Util.getValueByUrlStr(this.state.uploadParams, 'modularType'),
      }],
    };
    const resObj = await React.$asyncPost(this, '15030001', data);
    if (resObj.errorCode == 0) {
      this.setState({
        typeResultOBJ: resObj?.result,
      }, function () {
        this.uploadRecordListQuery(); // 查询数据
      });
    } else {
      message.error(resObj.errorMessage)
    }
  };
  //获取查询表单内的字典数据
  getFormDictData = async (formData) => {
    if (!formData || formData.length < 1) {
      return;
    }
    for (let i = 0; i < formData.length; i++) {
      //linkCode 有值，说明需要通过请求获取该表单类型下的字典
      if (formData[i].linkCode) {
        const data = {
          params: [{
            modularType: Util.getValueByUrlStr(this.state.uploadParams, 'modularType')
          }]
        };
        const resObj = await React.$asyncPost(this, formData[i].linkCode, data);
        if (resObj) {
          if (+resObj.errorCode === 0) {
            this.setState({
              [formData[i].code + "Dict"]: Util.addKeyValueToDataSource(resObj.result.Data)
            });
          } else {
            message.error(resObj.errorMessage)
          }
        }
      }
    }
  };
  //查询表头和表格数据
  uploadRecordListQuery = async (code = '', params = '') => {
    //显示加载框
    this.setState({
      loading: true,
    });
    let searchSize = this.state.pageSize;
    const { reqCode, pageSize = '' } = this.state.typeResultOBJ?.query || {};
    let { page } = this.state;
    let formValuesOBJ = this.getFormValues();
    // 返回有pageSize使用返回的参数
    if (pageSize) {
      searchSize = pageSize;
      this.setState({
        pageSize,
      })
    }
    let data = {
      params: params || [{
        modularType: Util.getValueByUrlStr(this.state.uploadParams, 'modularType'),
        componentName: Util.getValueByUrlStr(this.state.uploadParams, 'componentName'),
        ...formValuesOBJ,
      }],
      pagination: [{
        pageSize: searchSize,
        currentPage: params ? 1 : page,
      }],
    };
    const resObj = await React.$asyncPost(this, code || reqCode || '12050008', data);
    this.setState({
      loading: false,
    });
    if (resObj) {
      const errorCode = resObj.errorCode;
      if (+errorCode === 0) {
        const resListData = resObj.result && resObj.result.data;
        if (!resListData || resListData.length === 0) {
          message.warning('查询数据为空！');
          this.setState({
            columns: [],
            tableData: [],
            total: 0
          });
          return
        }
        this.setState({
          columns: resObj.result?.component || [],
          tableData: Util.addKeyValueToDataSource(resListData),
          total: resObj.result?.totalCount,
          scrollX: resObj.result?.scrollX,
        })
      } else {
        message.error(resObj.errorMessage)
      }
    }
  };
  //获取Form表单键值，处理日期值的格式
  getFormValues = () => {
    let formValues = this.props.form.getFieldsValue();
    if (formValues.startDate !== undefined) {
      formValues.startDate = moment(formValues?.startDate).format(dayFormat);
    }
    if (formValues.endDate !== undefined) {
      formValues.endDate = moment(formValues?.endDate).format(dayFormat);
    }
    return formValues;
  };
  // 分页器发生变化
  onPageChange = (page, pageSize) => {
    this.setState({
      page,
      pageSize,
    }, function () {
      this.uploadRecordListQuery();
    });
  }
  // 预览JSON
  preview = async (col, row) => {
    this.setState({
      loading: true,
    });
    const { tableColumnParam = {} } = col || {};
    const data = {
      params: [{
        ...row,
      }],
    };
    const resObj = await React.$asyncPost(this, tableColumnParam?.IFCode, data);
    if (+resObj.errorCode === 0) {
      this.setState({
        dialogContent: resObj?.result || '', //预览的内容
        dialogContentType: tableColumnParam?.dataDisplayMode || 'Plaintext', // 预览默然的类型
        visiblePreview: true,
        loading: false,
        tmpCol: col,
      });
      this.getFormDictData(resObj.result?.formData);//获取表单内的字典数据
    } else {
      this.setState({
        loading: false,
      });
      message.error(resObj.errorMessage)
    }
  }
  handleClose = () => {
    const { closeDetailFresh = false } = this.state.tmpCol;
    if (closeDetailFresh) {
      this.onPageChange(1, this.state.pageSize);
    }
    this.setState({
      visiblePreview: false
    });
  }
  setClick = async (name) => {
    let formValuesOBJ = this.getFormValues();
    let data = {
      params: [{
        modularType: Util.getValueByUrlStr(this.state.uploadParams, 'modularType'),
        componentName: Util.getValueByUrlStr(this.state.uploadParams, 'componentName'),
        ...formValuesOBJ,
      }],
    };
    let resObj;
    switch (name) {
      case 'export':
        this.setState({
          loading: true,
        });
        resObj = await React.$asyncPost(this, '12000001', data);
        if (+resObj.errorCode === 0) {
          const { origin } = location;
          window.open(origin + resObj.FileURL);
        }
        this.setState({
          loading: false,
        })
        break;
      case 'clearAll':
        this.setState({
          tableData: [],
        });
        this.props.form.resetFields();
        break;
      case 'refresh':
        resObj = await React.$asyncPost(this, '12000002', data);
        if (+resObj.errorCode === 0) {
          this.uploadRecordListQuery(resObj.result?.code, resObj.result?.params)
        }
        break;
    }
  }
  render () {
    const { getFieldDecorator } = this.props.form;
    const tableHeight = store.getState().tableHeight.y + 56 + 'px';
    // 搜索表单根据不同类型渲染
    const getFormConent = (item) => {
      switch (item?.typeCode) {
        case 'Date':
          return <DatePicker allowClear={false} placeholder={item?.placeholder} format={dayFormat} />
        case 'Input':
          return <Input placeholder={item?.placeholder} />;
        case 'Select':
          const dist = this.state[item?.code + "Dict"];
          return <Select allowClear showSearch>{
            dist && dist.map(data => {
              return (<Select.Option value={data?.code} key={data?.id}>{data?.desc}</Select.Option>)
            })
          }
          </Select>
      }
    }

    return (
      <div>
        <Spin spinning={this.state.loading} tip="加载中...">
          <Row justify='space-between' style={{ paddingTop: '10px' }}>
            <Form>
              {this.state.formData && this.state.formData.map((item, index) => {
                return (
                  <Col span={item?.col} key={index}>
                    <Form.Item {...{
                      labelCol: { span: item?.labelCol },
                      wrapperCol: { span: item?.wrapperCol }
                    }}
                      label={item?.descripts}
                    >
                      {getFieldDecorator(item?.code, {
                        initialValue: item?.typeCode === 'Date' ? moment(new Date, dayFormat).subtract(item?.default, 'days') : item?.default,
                        rules: [{ required: false, message: item?.placeholder }],
                      })(
                        getFormConent(item)
                      )}
                    </Form.Item>
                  </Col>
                )
              })}
            </Form>
            <Col span={4} style={{ textAlign: 'right', paddingRight: '20px' }}>
              <Button type='primary' onClick={() => this.uploadRecordListQuery()}>查询</Button>
              {this.state.buttonData.map((v) => {
                return <Button
                  type={v.typeDesc}
                  onClick={() => this.setClick(v['onClick'])}
                  style={{ margin: '0 6px' }}
                >{v.title}</Button>;
              })}
            </Col>
          </Row>
          <Row style={{ padding: 20, marginTop: -10 }}>
            <Table
              style={{ height: tableHeight, }}
              scroll={{
                x: this.state.scrollX || false,
                y: tableHeight,
              }}
              bordered={true}
              pagination={false}
              dataSource={this.state.tableData}
              columns={this.state.columns.map((col) => {
                return {
                  ...col,
                  ellipsis: true,
                  render: (text, record) => {
                    const { tableColumnType = '', tableColumnParam = {} } = col;
                    const { dataDisplayMaxLen = 200 } = tableColumnParam;
                    if (tableColumnType === 'L') { // 详情预览
                      return <span
                        style={{ color: '#1677ff', padding: '0 12px', textDecoration: 'underline', cursor: 'pointer' }}
                        onClick={() => {
                          this.preview(col, record);
                        }}> {text && text.length > dataDisplayMaxLen ? text.substring(0, dataDisplayMaxLen) : text}</span>
                    } else if (tableColumnType === 'P') { // JSON或者xml书籍展示
                      return <Popover content={text} title="详情" overlayStyle={{ maxWidth: '500px', wordBreak: 'break-all' }} placement="leftBottom">
                        <span
                          style={{ color: '#1677ff', padding: '0 12px', textDecoration: 'underline', cursor: 'pointer' }}
                        > {text && text.length > dataDisplayMaxLen ? text.substring(0, dataDisplayMaxLen) : text}</span>
                      </Popover>
                    } else if (tableColumnType === 'isHtml') { // 需要换行显示
                      return <span
                        dangerouslySetInnerHTML={{ __html: text }}
                      ></span>
                    } else {
                      return <span
                        style={{ padding: '0 12px' }}
                      >{text}</span>
                    }

                  }
                }
              })}
            />
          </Row>
          <Row style={{ marginTop: 40, paddingRight: 20 }}>
            <CommonPagination
              size={'small'}
              current={this.state.page}
              pageSize={this.state.pageSize}
              total={this.state.total}
              search={'search'}
              onShowSizeChange={this.onPageChange}
              dataSource={[]}
              onChange={this.onPageChange}
              loading={this.state.loading}
            />
          </Row>
        </Spin>
        <PreviewJson
          visibleDialog={this.state.visiblePreview}
          dialogContent={this.state.dialogContent}
          dialogContentType={this.state.dialogContentType}
          dialogFn={this.handleClose}
        ></PreviewJson>
      </div >
    );
  }
}
const publicTableDynamic = Form.create()(publicTableDynamicPage);
export default publicTableDynamic;
