/**
 * Created by mar105 on 2019-02-13.
 */
/* eslint-disable no-undef,import/first,prefer-destructuring,jsx-a11y/alt-text */
import React, { Component } from 'react';

import {
  DeleteOutlined,
  DownloadOutlined,
  EditOutlined,
  PlusOutlined,
  SaveOutlined,
  UploadOutlined,
} from '@ant-design/icons';

import { Modal, Upload, message, Radio, Button } from 'antd-v4';
import * as commonUtils from '../../utils/utils';
import * as commonServices from '../../services/services';
import commonConfig from '../../utils/config';
import * as commonBusiness from '../Common/commonBusiness';/* 单据业务功能 */
import StaticEditTable from '../Common/CommonTable';
import * as commonFunc from '../Common/commonFunc';
import AntdDraggableModal from '../Common/AntdDraggableModal';

const { confirm } = Modal;
export default class StatementInfo extends Component {
  /**   构造函数   */
  constructor(props) {
    super(props);
    this.state = {
      showUploadModal: false,
    };
  }

  /**   props改变的时候触发   */
  componentWillReceiveProps(nextProps) {
    let { reportColumn } = nextProps;
    const { app, visibleStatement } = nextProps;
    const reportName = commonFunc.showMessage(app.commonConst, 'reportName');/* 设计功能 */
    const sTemplateName= commonFunc.showMessage(app.commonConst, 'sTemplateName') || '模板名称' ;
    const sReportName= commonFunc.showMessage(app.commonConst, 'sReportName') || '报表名称' ;
    if (commonUtils.isEmptyArr(reportColumn) && visibleStatement) {
      const reportConfig = {};
      reportConfig.gdsconfigformslave = [{
        bVisible: true,
        sName: 'sReportName',
        bNotEmpty: true,
        showName: sReportName,
      }, {
        bVisible: true,
        sName: 'sReportPath',
        bReadOnly: true,
        showName: sTemplateName,
        iTag: 1,
      }];
      reportColumn = [{
        title: reportName,
        dataIndex: 'sReportName',
        width: 200,
      }, {
        title: sTemplateName,
        dataIndex: 'sReportPath',
        width: 239,
      }];
      reportConfig.bisMutiSelect = true; // 处理选择框消失问题
      this.getReportData();
      this.props.onSaveState({
        reportColumn, reportConfig,
      });
    }
  }

  /**   获取是否可用属性   */
  getDisabledProps = (name) => {
    const obj = {};
    obj.disabled = this.getMenuStatus(name);
    return obj;
  };

  /**   获取按钮属性   */
  getMenuStatus = (name) => {
    const { reportPropsEnabled } = this.props;
    let disabledData = []; /* 置灰按钮集合 */
    if (!reportPropsEnabled) {
      /* 初始状态 */
      disabledData = ['BtnSave', 'BtnUpload'];
    } else {
      /* 修改状态 */
      disabledData = ['BtnAdd', 'BtnUpd', 'BtnDel', 'BtnDownload'];
    }
    return (disabledData.findIndex(item => item === name) > -1);
  };
  /**   获取打印数据  */
  getReportData = async () => {
    const { sModelsId, token, formSrcRoute } = this.props;
    const dataUrl = `${commonConfig.file_host_ebc}printReport/getReport/${sModelsId}?sModelsId=${sModelsId}&sName=${formSrcRoute}`;
    const dataReturn = (await commonServices.getService(token, dataUrl)).data;
    if (dataReturn.code === 1) {
      const returnData = dataReturn.dataset.rows;
      this.props.onSaveState({ reportData: returnData, initialReportData: returnData });
    } else { /*   失败   */
      this.props.getServiceError(dataReturn);
    }
  };
  /** 上传文件改变时的状态 */
  handleUploadChange = (info) => {
    const { reportSelectedRowKeys, app } = this.props;
    if (reportSelectedRowKeys === undefined || reportSelectedRowKeys.length !== 1) {
      message.warn(commonFunc.showMessage(app.commonConst, 'selectedRowKeysNo')); /* 请先选择一条数据！ */
      return;
    }
    const { reportData } = this.props;
    const { file } = info;
    if (file.response) {
      if (file.response.code === 1) {
        /*   成功   */
        message.success(file.response.msg);
        const sReportPath = file.response.dataset.rows[0].savePathStr;
        const reportRow = reportData.filter(item => item.sId === reportSelectedRowKeys[0]);
        reportRow[0].sReportPath = sReportPath;
        reportRow[0].handleType = commonUtils.isEmpty(reportRow[0].handleType) ? 'update' : reportRow[0].handleType;
        this.props.onSaveState({ reportData });
      } else { /*   失败   */
        this.props.getServiceError({ msg: commonFunc.showMessage(app.commonConst, 'reportDesign') + file.response }); /* 报表设计 */
      }
    }
  };
  handleBtnAdd = async (name) => {
    const {
      sModelsId, [`${name}Data`]: tableData = [],
    } = this.props;
    let tableDataRow = await this.props.onDataRowAdd(name, true);
    if (commonUtils.isEmptyObject(tableDataRow)) {
      tableDataRow = {};
      tableDataRow.sId = commonUtils.createSid();
      tableDataRow.handleType = 'add';
      tableDataRow.key = tableDataRow.sId;
    }
    tableDataRow.sFormId = sModelsId;
    tableData.push(tableDataRow);
    this.props.onSaveState({ [`${name}Data`]: tableData, reportPropsEnabled: true });
  };
  handleBtnUpd = () => {
    this.getReportData();
    this.props.onSaveState({ reportPropsEnabled: true });
  };
  handleBtnSave = () => {
    const {
      reportData, reportDelData, reportConfig, app,
    } = this.props;
    const data = [];
    if (!commonBusiness.validateTable(reportConfig, reportData, this.props)) {
      return;
    }
    data.push(commonBusiness.mergeData('report', 'sysreport', reportData, reportDelData));
    this.handleSaveData({ data, sClientType: '1', optName: commonFunc.showMessage(app.commonConst, 'reportDesign') });
  };
  handleSaveData = async (params) => {
    const {
      token, masterData, optName,
    } = this.props;
    const returnData = await commonBusiness.saveData({ token, value: params, sModelsId: 100 });
    if (returnData.code === 1) {
      this.props.onSaveState({
        reportPropsEnabled: false, currentId: masterData.sId,
      });
      this.getReportData();
    } else {
      this.props.getServiceError(optName + returnData);
    }
  };
  handleBtnDel = () => {
    const { reportSelectedRowKeys } = this.props;
    const props = { ...this.props };
    const onSaveStateOk = this.props.onSaveState;
    confirm({
      title: '确定要删除？',
      onOk() {
        props.onDataRowDel('report', false, reportSelectedRowKeys);
        onSaveStateOk({ reportPropsEnabled: true });
      },
      onCancel() {
      },
    });
  };
  handleBtnDownload = () => {
    const {
      reportSelectedRowKeys, reportData, sModelsId, app, formSrcRoute,
    } = this.props;
    if (reportSelectedRowKeys === undefined || reportSelectedRowKeys.length !== 1) {
      message.warn(commonFunc.showMessage(app.commonConst, 'selectedRowKeysNo'));/* 请先选择一条数据 */
      return;
    }
    const { token } = this.props.app;
    const dataSelect = reportData.filter(item => item.sId === reportSelectedRowKeys[0]);
    const { sReportPath } = dataSelect[0];
    const urlPrint = `${commonConfig.file_host_ebc}file/downloadReport?sModelsId=${sModelsId}&token=${token}&savePathStr=${sReportPath}&sName=${formSrcRoute}`;
    window.open(urlPrint);
  };
  /* 置顶 */
  handleBtnTop = (name) => {
    const {
      [`${name}SelectedRowKeys`]: reportSelectedRowKeys, [`${name}Data`]: tableData, app,
    } = this.props;
    if (reportSelectedRowKeys === undefined || reportSelectedRowKeys.length !== 1) {
      message.warn(commonFunc.showMessage(app.commonConst, 'selectedRowKeysNo'));/* 请先选择一条数据 */
      return;
    }
    const iIndex = tableData.findIndex(item => item.sId === reportSelectedRowKeys[0]);/* 选中第一个节点的下标 */
    if (iIndex === 0) {
      message.warn(commonFunc.showMessage(app.commonConst, 'NoTop')); /* 无需置顶 */
      return;
    } else {
      tableData[iIndex].iOrder = 1;/* 初始为1； */
    }
    let initNum = 2;
    tableData.forEach((item, index) => {
      item.handleType = commonUtils.isEmpty(item.handleType) ? 'update' : item.handleType;
      if (index !== iIndex) {
        tableData[index] = { ...item, iOrder: initNum };
        initNum += 1;
      }
    });
    this.props.onSaveState({ [`${name}Data`]: tableData });
    this.handleBtnSave();
  };
  handleShowUpload = () => {
    const { reportSelectedRowKeys, app , sModelsId, formSrcRoute} = this.props;
    if (reportSelectedRowKeys === undefined || reportSelectedRowKeys.length !== 1) {
      message.warn(commonFunc.showMessage(app.commonConst, 'selectedRowKeysNo'));
      return;
    }
    // 根据用户语言决定流程
    if (app.userinfo.sLanguage === 'sChinese') {
      // 中文用户直接触发上传
      this.uploadRef.upload.uploader.fileInput.click();
    } else {
      // 英文用户显示选择类型弹窗
      this.setState({ showUploadModal: true });
    }
  };

  handleUploadConfirm = () => {
    this.setState({ showUploadModal: false }); // 关闭Modal
    if (this.uploadRef) {
      this.uploadRef.upload.uploader.fileInput.click();
    } else {
      message.error('Error');
    }
  };

  handleOk = () => {
    this.handleBtnSave();
    this.props.onSaveState({
      visibleStatement: false,
    });
  };

  handleCancel = () => {
    this.getReportData();
    this.props.onSaveState({
      visibleStatement: false,
    });
  };

  /**   渲染   */
  render() {
    const {
      sModelsId, app, sTabId, formSrcRoute, reportPropsEnabled,
    } = this.props;
    const pane = app.panes.filter(paneTmp => paneTmp.key === sTabId)[0];
    const { token } = this.props.app;
    // 使用state管理reportType，默认为'zh'
    const reportType = this.reportType || 'sChinese';
    const outProps = {
      action: `${commonConfig.file_host_ebc}file/uploadReport?sModelsId=${sModelsId}&token=${token}&sName=${formSrcRoute}&reportType=${reportType}`,      onChange: this.handleUploadChange,
      accept: '.xlsx',
      showUploadList: false,
      beforeUpload: () => {
        if (!this.props.reportPropsEnabled) return false;
      },
    };
    const reportProps = {
      ...commonBusiness.getTableTypes('report', this.props),
      onDoubleClick: undefined,
      sUseInfo: '',
      enabled: reportPropsEnabled,
    };
    const DesignFunc = commonFunc.showMessage(app.commonConst, 'DesignFunc');/* 设计功能 */
    const BtnAdd = commonFunc.showMessage(app.commonConst, 'BtnAdd');/* 新增 */
    const BtnUpd = commonFunc.showMessage(app.commonConst, 'BtnUpd');/* 修改 */
    const BtnDel = commonFunc.showMessage(app.commonConst, 'BtnDel');/* 删除 */
    const BtnDownload = commonFunc.showMessage(app.commonConst, 'BtnDownload');/* 下载 */
    const BtnUpload = commonFunc.showMessage(app.commonConst, 'BtnUpload');/* 上传 */
    const BtnSave = commonFunc.showMessage(app.commonConst, 'BtnSave');/* 保存 */
    const btnTop = commonFunc.showMessage(app.commonConst, 'setTop');/* 置顶 */
    const sLanguage = app.userinfo?.sLanguage;
    const BtnSure = commonFunc.showMessage(app.commonConst, 'BtnSure');/* 置顶 */
    const modalTitle = sLanguage === 'sEnglish' ? 'Please confirm the upload' : '请确认上传';

    const sChinseReport =  sLanguage === 'sEnglish' ? 'Chinese Report' : '中文报表';

   const sEnglishReport =  sLanguage === 'sEnglish' ? 'English Report' : '英文报表';
    return (
      <div>
        {(pane?.notCurrentPane ? false : this.props.visibleStatement) ?
          <AntdDraggableModal
            title={DesignFunc}
            visible={pane?.notCurrentPane ? false : this.props.visibleStatement}
            bodyStyle={{ padding: 12, maxHeight: '420px' }}
            onOk={this.handleOk}
            onCancel={this.handleCancel}
          >
            <div id="StatementInfo">
              <div className="billToolBar">
                <div className="toolBar___22SoH">
                  <ul className="ant-menu billBtnGroup ant-menu-light ant-menu-root ant-menu-horizontal" style={{ backgroundColor: 'rgb(100, 100, 100)', color: 'rgb(255,255,255)' }} >
                    <li>
                      <a{...this.getDisabledProps('BtnAdd')} onClick={() => this.handleBtnAdd('report')}>  <PlusOutlined />{BtnAdd}</a>
                    </li>
                    <li>
                      <a{...this.getDisabledProps('BtnUpd')} onClick={() => this.handleBtnUpd()}> <EditOutlined />{BtnUpd}</a>
                    </li>
                    <li>
                      <a{...this.getDisabledProps('BtnDel')} onClick={() => this.handleBtnDel()}> <DeleteOutlined />{BtnDel}</a>
                    </li>
                    <li>
                      <a{...this.getDisabledProps('BtnDownload')} onClick={() => this.handleBtnDownload()}> <DownloadOutlined />{BtnDownload}</a>
                    </li>
                    <li>
                      <a
                        {...this.getDisabledProps('BtnSave')}
                        onClick={() => setTimeout(() => {
                          this.handleBtnSave();
                        }, 500)}
                      > <SaveOutlined />{BtnSave}
                      </a>
                    </li>
                    <li>
                      <a {...this.getDisabledProps("BtnUpload")} onClick={this.handleShowUpload}>
                        <UploadOutlined />
                        {BtnUpload}
                      </a>
                      <Modal
                        title={modalTitle}
                        visible={this.state.showUploadModal}
                        footer={[
                          <Button key="submit" type="primary" onClick={this.handleUploadConfirm}>
                            {BtnSure}
                          </Button>,
                        ]}
                        width={500} // 设置固定宽度
                        bodyStyle={{
                          padding: "16px 24px", // 调整内边距
                          maxHeight: "60vh", // 限制最大高度
                          overflow: "auto", // 添加滚动条
                        }}
                      >
                        <Radio.Group
                          defaultValue="zh"
                          onChange={e => {
                            this.reportType = e.target.value;
                          }}
                        >
                          <Radio value="sChinese">{sChinseReport}</Radio>
                          <Radio value="sEnglish">{sEnglishReport}</Radio>
                        </Radio.Group>
                      </Modal>

                      <Upload {...outProps} style={{ display: "none" }} ref={ref => (this.uploadRef = ref)}>
                        <a style={{ display: "none" }}></a>
                      </Upload>
                    </li>
                    <li>
                      <a{...this.getDisabledProps('BtnSave')} onClick={() => this.handleBtnTop('report')}> <SaveOutlined />{btnTop}</a>
                    </li>
                  </ul>
                </div>
              </div>
              <StaticEditTable {...reportProps} />
            </div>
          </AntdDraggableModal>
          : ''}
      </div>
    );
  }
}
