/**
 * 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 { Form } from '@ant-design/compatible';
// import '@ant-design/compatible/assets/index.css';
import { Button, Layout, message, Spin } from 'antd-v4';
import StaticEditTable from '../Common/CommonTable';
import * as commonBusiness from '../Common/commonBusiness';
import CommonBase from '../Common/CommonBase';
import CommonClassifyEvent from '../Common/CommonClassifyEvent';
import * as commonFunc from '../Common/commonFunc';
import commonConfig from '../../utils/config';
import * as commonUtils from '../../utils/utils';/* 通用单据方法 */ /* 通用单据方法 */
// import CommonListEvent from '../Common/CommonListEvent';

const { Content } = Layout;
class FilfileManageInfoComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
    };
    this.form = {}; /*   表单对象   */
  }
  handleOk = async (name) => {
    const { app, slaveData, slaveDelData } = this.props;
    try {
      await this.props.onSubmit();/* 通用保存 */
    } catch (error) {
      return;
    }
    /*
    slaveData:文件上传数据
    slaveDelData:文件已删除数据
    app.currentPane.sSrcSlaveId：工单控制表选中行sId
     */
    this.props.app.currentPane.onFilfileOk(name, app.currentPane.config, slaveData, app.currentPane.sSrcSlaveId, slaveDelData);
  };

  handleCancel = (name) => {
    this.props.app.currentPane.onFilfileCancel(name);
  };
  /**   上传后执行函数    */
  handleBeforeUpload = (file) => {
    const { type = '' } = file;
    const { config = {} } = this.props;
    const { sActiveKey = '' } = config;
    if (sActiveKey === 'image') {
      if (!type.startsWith('image')) {
        message.warning('该模块只允许上传【图片】！');
        return false;
      }
    } else if (sActiveKey === 'pdf') {
      if (type !== 'application/pdf') {
        message.warning('该模块只允许上传【PDF】！');
        return false;
      }
    } else if (sActiveKey.includes('image') && sActiveKey.includes('pdf')) {
      if (!type.startsWith('image') && type !== 'application/pdf') {
        message.warning('该模块只允许上传【图片/PDF】！');
        return false;
      }
    }
    return true;
  };
  /**   上传后执行函数(单一上传）    */
  handleUploadChangeSingle = (info, name) => {
    const { app } = this.props;
    const { currentPane } = app;
    const { file } = info;
    if (file.response && file.response.code === 1) {
      const sPicturePath = file.response.dataset.rows[0].savePathStr;
      const { masterData } = this.props;
      let { [`${name}Data`]: tableData } = this.props;
      if (commonUtils.isEmptyArr(tableData)) {
        tableData = [];
      }
      const tableDataRow = this.props.onDataRowAdd(name, true);/* 选中行 */
      if (commonUtils.isNotEmptyObject(masterData)) {
        tableDataRow.sProductNo = masterData.sProductNo !== undefined ? masterData.sProductNo : '';
        tableDataRow.sProductName = masterData.sProductName !== undefined ? masterData.sProductName : '';
      }
      tableDataRow.iOrder = tableData.length + 1;
      tableDataRow.sSrcNo = commonUtils.isNotEmptyObject(currentPane) ? currentPane.sSrcNo : '';
      tableDataRow.sSrcFormId = commonUtils.isNotEmptyObject(currentPane) ? currentPane.sSrcFormId : '';
      tableDataRow.sSrcId = commonUtils.isNotEmptyObject(currentPane) ? currentPane.sSrcId : '';
      tableDataRow.sSrcSlaveId = commonUtils.isNotEmptyObject(currentPane) ? currentPane.sSrcSlaveId : '';
      tableDataRow.sPicturePath = file.response && file.response.code === 1 ? sPicturePath : '';
      tableDataRow.spicture = tableDataRow.sPicturePath;
      tableDataRow.sFileName = file.response && file.response.code === 1 ? file.name : '';
      tableData.push(tableDataRow);
      this.props.onSaveState({ [`${name}Data`]: tableData });
    } else if (file.response && file.response.code === -1) {
      message.error(file.response.msg);
    }
  };

  /* 多文件上传 */
  handleUploadChange = (info, name) => {
    const { app } = this.props;
    const { currentPane } = app;
    const { fileList: fileListOlld } = info;
    const fileList = fileListOlld.filter(item => item.status);
    let uploadDone = true;
    fileList.forEach((item) => {
      if (item.status !== 'done') {
        uploadDone = false;
      }
    });
    if (uploadDone) {
      let { [`${name}Data`]: tableData } = this.props;
      if (commonUtils.isEmptyArr(tableData)) {
        tableData = [];
      }
      fileList.forEach((file) => {
        if (file.response && file.response.code === 1) {
          const sPicturePath = file.response.dataset.rows[0].savePathStr;
          const { masterData } = this.props;
          const tableDataRow = this.props.onDataRowAdd(name, true);/* 选中行 */
          if (commonUtils.isNotEmptyObject(masterData)) {
            tableDataRow.sProductNo = masterData.sProductNo !== undefined ? masterData.sProductNo : '';
            tableDataRow.sProductName = masterData.sProductName !== undefined ? masterData.sProductName : '';
          }
          tableDataRow.iOrder = tableData.length + 1;
          tableDataRow.sSrcNo = commonUtils.isNotEmptyObject(currentPane) ? currentPane.sSrcNo : '';
          tableDataRow.sSrcFormId = commonUtils.isNotEmptyObject(currentPane) ? currentPane.sSrcFormId : '';
          tableDataRow.sSrcId = commonUtils.isNotEmptyObject(currentPane) ? currentPane.sSrcId : '';
          tableDataRow.sSrcSlaveId = commonUtils.isNotEmptyObject(currentPane) ? currentPane.sSrcSlaveId : '';
          tableDataRow.sPicturePath = file.response && file.response.code === 1 ? sPicturePath : '';
          tableDataRow.spicture = tableDataRow.sPicturePath;
          tableDataRow.sFileName = file.response && file.response.code === 1 ? file.name : '';
          tableData.push(tableDataRow);
          // this.props.onSaveState({ [`${name}Data`]: tableData, enabled: true });
        } else if (file.response && file.response.code === -1) {
          message.error(file.response.msg);
        }
      });
      this.props.onSaveState({ [`${name}Data`]: tableData });
    }
  };

  /**   通用下载    */
  handleDownload = (name, flag, tableSelectedRowKeys) => {
    const {
      [`${name}Data`]: tableData, sModelsId, app,
    } = this.props;
    if (tableSelectedRowKeys === undefined || tableSelectedRowKeys.length !== 1) {
      message.warn(commonFunc.showMessage(app.commonConst, 'selectedRowKeysNo'));/* 请先选择一条数据 */
      return;
    }
    const dataSelect = tableData.filter(item => item.sId === tableSelectedRowKeys[0]);
    const { token } = this.props.app;
    const { sPicturePath } = dataSelect[0];
    const urlPrint = `${commonConfig.file_host}file/download?sModelsId=${sModelsId}&token=${token}&savePathStr=${sPicturePath}`;
    window.open(urlPrint);
  };
  render() {
    return (
      <div>
        <Spin spinning={false}>
          <div>
            <FilfileManageComponent
              {...this.props}
              onModalOk={this.handleOk}
              onModalCancel={this.handleCancel}
              onUploadChange={this.handleUploadChange}
              onBeforeUpload={this.handleBeforeUpload}
              onDataRowDownload={this.handleDownload}
              // onDataChange={this.handleTableChange}
            />
          </div>
        </Spin>
      </div>
    );
  }
}

const FilfileManageComponent = Form.create({
  mapPropsToFields(props) {
    const { masterData } = props;
    const obj = commonFunc.mapPropsToFields(masterData, Form);
    return obj;
  },
})((props) => {
  const {
    form, onReturnForm,
  } = props;
  /*   回带表单   */
  onReturnForm(form);
  const filfilemanageProps = {
    ...commonBusiness.getTableTypes('slave', props),
    uploadFileTypeVerification: true,
    tableProps: { setUpload: true, setDownload: true },
    enabled: true,
  };
  const BtnSure = commonFunc.showLocalMessage(props, "BtnSure", "确定");
  const BtnCancel = commonFunc.showLocalMessage(props, "BtnCancel", "取消");
  return (
    <Form >
      <Layout>
        <Layout>
          <div id="modalChooseProcess">
            <Content className="xly-bill-list xly-normal-list">
              <StaticEditTable {...filfilemanageProps} setOpterationColumn="Y" footer="hidden" />
            </Content>
          </div>
        </Layout>
        <div style={{ textAlign: 'right', marginRight: '9px', marginBottom: '9px' }}>
          <Button key="back" style={{ marginRight: '8px' }} onClick={props.onModalCancel.bind(this, 'visibleFilfile')}>{BtnCancel}</Button>
          <Button type="primary" onClick={props.onModalOk.bind(this, 'visibleFilfile')}>{BtnSure}</Button>
        </div>
      </Layout>
    </Form>
  );
});

export default CommonBase(CommonClassifyEvent(FilfileManageInfoComponent));

