import React from 'react';
import { connect } from 'dva';
import { Button, Input, Row, Col, Form, Table, message, Upload, Icon, Tabs } from 'antd';
import {
  initFilter, getOnlyPropertyData, getDataFieldValue, empty
} from "../../utils/common";
import config from "../../config";
import storage from '../../utils/storage';
const TabPane = Tabs.TabPane;

const { TextArea } = Input;

class ImportPage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      importUrl: '',
      selectedRowKeys: [],
      importConfig: {}
    };
  };

  componentDidMount() {
    this.props.form.resetFields();
    this.loadData();
  }

  componentWillReceiveProps(NextProps) {
    if (NextProps.custom['importClick' + NextProps.configCode]) {
      this.props.form.resetFields();
      this.loadData();
      this.props.dispatch({
        type: 'custom/save',
        payload: {
          ['importClick' + NextProps.configCode]: false
        },
      });
    }

    if (NextProps.custom[NextProps.clickKey]) {
      this.props.form.resetFields();
      this.loadData();
      this.props.dispatch({
        type: 'custom/save',
        payload: {
          [NextProps.clickKey]: false
        },
      });
    }
  }

  loadData = () => {
    const { dispatch, configCode } = this.props;
    if (configCode) {
      const json = initFilter(this.props.login.OrgId, configCode);
      dispatch({
        type: 'import/getImportConfig',
        payload: json,
        onComplete: (ret) => {
          if (ret) {
            let jsFile = '';
            if (ret.Nav_EditForm) {
              jsFile = ret.Nav_EditForm.JS_FILES;
            }
            this.setState({
              data: [],
              importConfig: ret,
              jsFile: jsFile,
              selectedRowKeys: [],
              messages: '',
              updateLoadFileList: [],
            });
          }
        }
      });
    }
  };

  onSelectChange = (selectedRowKeys, selectedRows) => {  // 选择菜单行
    this.setState({ selectedRowKeys: selectedRowKeys });
  };

  getSubTable = (subTables, updateParentRow, parentRow) => {
    let isError = false;
    if (parentRow && subTables && updateParentRow) {
      subTables.forEach((n, i) => {
        if (isError) return;
        if (n.NavProperty) {
          const data = parentRow[n.NavProperty];
          if (data && data.length) {
            const tmps = [];
            data.forEach((n1, i1) => {
              if (isError) return;
              if (n && n.Nav_Columns) {
                const list = n.Nav_Columns.filter(t => !t.Nav_EditColumn || t.Nav_EditColumn.IS_DEFAULT);
                list.forEach((n3, i3) => {
                  if (n3.Nav_EditColumn && n3.Nav_EditColumn.REQUIRED) {
                    const v = getDataFieldValue(n1, n3.Nav_EditColumn.FIELD_NAME, null);
                    if (empty(v, true) && !isError) {
                      message.error('请填写' + n3.Nav_EditColumn.LABEL);
                      isError = true;
                    }
                  }
                });
              }
              if (isError) return;
              const r = getOnlyPropertyData(n1);
              if (n.Nav_SubTables && n.Nav_SubTables.length) {
                this.getSubTable(n.Nav_SubTables, r, n1);
              }
              tmps.push(r);
            });
            updateParentRow[n.NavProperty] = tmps;
          }
        }
      });
    }
    return isError;
  }

  handleOk = () => {
    const { form, dispatch } = this.props;
    const { validateFieldsAndScroll } = form;
    validateFieldsAndScroll((errors, values) => {
      if (errors) return;
      let updateData = [];
      let isError = false;
      const data = this.state.data;
      const importConfigTable = this.state.importConfig ? this.state.importConfig.Nav_ImportTable : null;
      let url = this.state.importConfig && this.state.importConfig.Nav_ImportConfig ? this.state.importConfig.Nav_ImportConfig.API_URL : null;

      if (data && data.length) {
        data.forEach((n, i) => {
          if (isError) return;
          let isSelect = false;
          if (this.state.selectedRowKeys && this.state.selectedRowKeys.length) {
            isSelect = this.state.selectedRowKeys.includes(n.ID);
          }
          if (!isSelect) return;
          if (importConfigTable && importConfigTable.Nav_Columns) {
            const list = importConfigTable.Nav_Columns.filter(t => !t.Nav_EditColumn || t.Nav_EditColumn.IS_DEFAULT);
            list.forEach((n1, i1) => {
              if (n1.Nav_EditColumn && n1.Nav_EditColumn.REQUIRED) {
                const v = getDataFieldValue(n, n1.Nav_EditColumn.FIELD_NAME, null);
                if (empty(v, true) && !isError) {
                  if (empty(v, true)) {
                    message.error('请填写行[' + (i + 1) + ']' + n1.Nav_EditColumn.LABEL);
                  }
                  else {
                    message.error('行[' + (i + 1) + ']' + n1.Nav_EditColumn.LABEL + '数据异常');
                  }

                  isError = true;
                }
              }
            });
          }
          if (isError) return;
          var d = getOnlyPropertyData(n);
          if (importConfigTable && importConfigTable.Nav_SubTables && importConfigTable.Nav_SubTables.length) {
            const tmpE = this.getSubTable(importConfigTable.Nav_SubTables, d, n);
            if (tmpE) {
              isError = tmpE;
            }
          }
          updateData.push(d);
        });
      }
      if (isError) return;
      if (!updateData.length) {
        message.error('请选择导入文件或者记录');
        return;
      }
      updateData.forEach((n1, i1) => {
        const tmpError = this.handleBeforeSaveEvent(n1);
        if (tmpError) {
          isError = true;
        }
      });
      if (isError) return;


      if (url) {
        this.setState({ isSaving: true })
        dispatch({
          type: 'app/getDataByPost',
          payload: { Nav_Details: updateData },
          url: url,
          onComplete: (ret) => {
            if (ret) {
              message.success('执行成功');
              this.setState({
                data: [],
                selectedRowKeys: [],
                messages: '',
              });
              setTimeout(() => { this.setState({ isSaving: false }) }, 1000)
            }
          }
        });
      }
      else {
        let completeCount = 0;
        let allSuccess = true;
        url = this.state.importConfig && this.state.importConfig.Nav_ImportTable && this.state.importConfig.Nav_ImportTable.Nav_PageEdit ? this.state.importConfig.Nav_ImportTable.Nav_PageEdit.API_URL : null;
        if (!url) {
          message.error('请配置API');
          return;
        }
        this.setState({ isSaving: true })
        updateData.forEach((n, i) => {
          dispatch({
            type: 'app/getDataByPost',
            payload: n,
            url: url,
            onComplete: (ret) => {
              completeCount++;
              if (!ret) {
                allSuccess = false;
              }
              if (completeCount == updateData.length) {
                this.setState({
                  data: [],
                  selectedRowKeys: [],
                  messages: '',
                });
                if (allSuccess) {
                  message.success('执行成功');
                }
                setTimeout(() => { this.setState({ isSaving: false }) }, 1000);
              }
            }
          });


        });
      }


    })
  };

  getDynJsFunc = (e) => {
    let func = null;
    //取静态公共方法
    if (!func) {
      const jsFile = this.getStaticJsFunc();
      func = jsFile[e];
    }
    //取props中的动态js方法
    if (!func && this.props.dynJsFunc) {
      func = this.props.dynJsFunc[e];
    }

    //取加载data中的动态方法
    if (!func && this.props && this.props.data && this.props.data.dynJsFunc) {
      func = this.props.data.dynJsFunc[e];
    };
    //取动态js中的动态方法
    if (this.state.jsFile) {
      const jsFiles = this.state.jsFile.split(',');
      if (jsFiles) {
        jsFiles.map(t => {
          if (func) return;
          const jsFile = require('../../files/edit/' + t).default;
          func = jsFile[e];
        });
      };
    };
    return func;
  };

  getStaticJsFunc = () => {
    return {
    };
  };

  handleBeforeSaveEvent = (data) => {
    const func = this.getDynJsFunc('onBeforeSave');
    if (typeof func === 'function') {
      return func({
        data: this.props.data,
        stateData: data,
        pageCode: (this.state.importConfig && this.state.importConfig.Nav_ImportTable ? this.state.importConfig.Nav_ImportTable.CODE : null),
        custom: this.props.custom,
      });
    }
  };

  fillImportData = (ret) => {
    if (!ret) {
      this.setState({
        data: [],
        selectedRowKeys: [],
        messages: '',
      })
      return;
    }
    if (ret.ErrorMessage) {
      this.setState({
        messages: ('错误：' + ret.ErrorMessage)
      });
    }
    let messages = '';
    if (ret.Data && ret.Data.MessageList && ret.Data.MessageList.length) {
      var tmps = [];
      ret.Data.MessageList.forEach((n, i) => {
        tmps.push(n);
      });
      messages = tmps.join('\n');
    }
    const selectedRowKeys = [];
    if (ret.Data && ret.Data.Data) {
      ret.Data.Data.forEach((n, i) => {
        selectedRowKeys.push(n.ID);
      });
    }
    this.setState({
      data: (ret.Data && ret.Data.Data ? ret.Data.Data : []),
      selectedRowKeys,
      messages
    });
  }


  getSubTables = (record, subTables) => {
    return subTables.map(t => {
      const tableColumns = this.getColumns(t);
      if (tableColumns) {
        return <Table
          rowKey="ID"
          pagination={false}
          dataSource={record[t.NavProperty]}
          columns={tableColumns}
          rowSelection={false}
          scroll={{ x: "100%" }}
          expandedRowRender={(t.Nav_SubTables && t.Nav_SubTables.length ? (e) => {
            return this.getSubTables(e, t.Nav_SubTables)
          } : null)}
        />
      }
    });
  }

  getColumns = (table) => {
    if (table && table.Nav_Columns) {
      const enums = this.props.app.enums;
      const list = table.Nav_Columns.filter(t => !t.Nav_EditColumn || t.Nav_EditColumn.IS_DEFAULT);
      return list.map(t => {
        if (t.Nav_EditColumn) {
          if (t.Nav_EditColumn.CONTROL_TYPE === 2) {//时间选择
            return {
              title: <>{t.Nav_EditColumn.REQUIRED ? <span style={{ color: 'red' }}>*</span> : null}{t.Label}</>, dataIndex: t.FieldName, key: t.FieldName, render: (text, record, index) => {
                if (text) {
                  return text.toString().substring(0, 10);
                }
              }
            };
          }
          else if (t.Nav_EditColumn.CONTROL_TYPE === 3) {//下拉选择
            if (t.Nav_EditColumn.ENUM) {
              return {
                title: <>{t.Nav_EditColumn.REQUIRED ? <span style={{ color: 'red' }}>*</span> : null}{t.Label}</>, dataIndex: t.FieldName, key: t.FieldName, render: (text, record, index) => {
                  return enums && enums[t.Nav_EditColumn.ENUM] && enums[t.Nav_EditColumn.ENUM].enums ? enums[t.Nav_EditColumn.ENUM].enums[text] : null;
                }
              };
            }
          }
          else if (t.Nav_EditColumn.CONTROL_TYPE === 4) {//单项选框
            return {
              title: <>{t.Nav_EditColumn.REQUIRED ? <span style={{ color: 'red' }}>*</span> : null}{t.Label}</>, dataIndex: t.FieldName, key: t.FieldName, render: (text, record, index) => {
                return text ? '是' : '否';
              }
            };
          }
          else if (t.Nav_EditColumn.CONTROL_TYPE === 5) {//多项选框
            return {
              title: <>{t.Nav_EditColumn.REQUIRED ? <span style={{ color: 'red' }}>*</span> : null}{t.Label}</>, dataIndex: t.FieldName, key: t.FieldName, render: (text, record, index) => {
                return text ? '是' : '否';
              }
            };
          }
        }
        return {
          title: <>{t.Nav_EditColumn && t.Nav_EditColumn.REQUIRED ? <span style={{ color: 'red' }}>*</span> : null}{t.Label}</>, dataIndex: t.FieldName, key: t.FieldName, render: (text, record, index) => {
            if (text !== null && text !== undefined) {
              const tmp = text.toString();
              if (tmp.length > 10) {
                return <span title={tmp}>{tmp.substring(0, 10) + '...'}</span>;
              }
              else {
                return tmp;
              }
            }
          }
        };
      });
    }
  };

  getDataUpdate = (update) => {
    if (update) {
      this.setState({ importUrl: 'api/PF/Import/ImportAndUpdate' })
    } else {
      this.setState({ importUrl: 'api/PF/Import/GetImportData' })
    }

  }



  getMainTable = () => {
    const importConfig = this.state.importConfig;
    if (importConfig && importConfig.Nav_ImportTable) {
      const { selectedRowKeys } = this.state;
      const rowSelection = {
        selectedRowKeys: selectedRowKeys,
        fixed: false,
        columnWidth: 20,
        onChange: this.onSelectChange,
        hideDefaultSelections: false
      };
      const tableColumns = this.getColumns(importConfig.Nav_ImportTable);
      if (tableColumns) {
        let rowno = {
          title: "序号",
          render: (text, record, index) => `${index + 1}`,
        };
        tableColumns.unshift(rowno);
        return <Table
          rowKey="ID"
          pagination={false}
          dataSource={this.state.data}
          columns={tableColumns}
          rowSelection={rowSelection}
          scroll={{ x: "100%" }}
          expandedRowRender={(importConfig.Nav_ImportTable.Nav_SubTables && importConfig.Nav_ImportTable.Nav_SubTables.length ? (e) => {
            return this.getSubTables(e, importConfig.Nav_ImportTable.Nav_SubTables)
          } : null)}
        />
      }
    }
  }

   getRequestHeaders =() =>{
    // 请求参数
    const addHeader = 'Bearer ' + storage('lacal').getItem('accessToken').val
    const userId = storage('lacal').getItem('userid').val
    const user = storage('lacal').getItem('loginUserVerify').val
    const RootOrgId = storage('lacal').getItem('RootOrgId').val
    const orgId = storage('lacal').getItem('webOrgId').val
    const Tenant = storage('lacal').getItem('Tenant').val
    const headers = {
      // 'Content-Type': type === 'post' ? 'application/json' : 'application/x-www-form-urlencoded',
      Authorization: addHeader,
      userid: userId,
      username: user ? user.username : '',
      RootOrgId,
      orgId,
      Tenant:Tenant
    }
    return headers
  }


  render() {

    const { configCode, delFlag } = this.props;
    const disabled = !this.state.importConfig || !this.state.importConfig.Nav_ImportConfig ||
      !this.state.importConfig.Nav_ImportTable || !this.state.importConfig.Nav_ImportTable.Nav_Columns;
    let url = this.state.importUrl;
    const that = this;
    const uploadProps = {
      name: 'file',
      action: config.serviceHost(url),
      data: { OrgId: this.props.login.OrgId, ImportConfigCode: configCode, delFlag: delFlag },
      fileList: this.state.updateLoadFileList,
      accept: '.xls,.xlsx',
      headers: this.getRequestHeaders(),
      onChange(info) {
        that.setState({
          updateLoadFileList: info.fileList,
        });

        if (info.file.status === 'done') {
          if (info.file.response.IsSuccessful) {
            if (url == 'api/PF/Import/ImportAndUpdate') {
              message.info(`${info.file.name} 导入并保存成功`);
            }
            that.fillImportData(info.file.response);
          } else {
            message.error(`${info.file.response.ErrorMessage} `);
          }
        } else if (info.file.status === 'error') {
          if (info.file.response && info.file.response.ErrorMessage) {
            message.error(`${info.file.name} 导入错误，详情：${info.file.response.ErrorMessage}`);
          }
          else {

            message.error(`${info.file.name} 导入错误`);
          }

        }
      },
    };



    return (
      <div>
        <Form>
          <Tabs defaultActiveKey="1" >
            <TabPane tab="导入并提交" key="1">
              <Row style={{ marginTop: '10px' }}>
                <Upload {...uploadProps}>
                  <Button disabled={disabled || this.state.isSaving} onClick={() => this.getDataUpdate(true)}>
                    <Icon type="upload" /> 选择导入文件
                  </Button>
                </Upload>

              </Row>
              <Row style={{ marginTop: '20px' }}>
                {
                  this.getMainTable()
                }
              </Row>
            </TabPane>
            {/* <TabPane tab="导入数据" key="2">
                <Row style={{marginTop:'10px'}}>
                  <Upload {...uploadProps}>
                    <Button disabled={disabled||this.state.isSaving} onClick={()=>this.getDataUpdate(false)}>
                      <Icon type="upload" /> 选择导入文件
                    </Button>
                  </Upload>
                </Row>
                <Row style={{marginTop:'20px'}}>
                  {
                    this.getMainTable()
                  }
                </Row>
                <Row style={{marginTop:'20px'}}>
              <Col style={{ textAlign: 'right' }}>
                <Button type={'primary'} icon={'save'} onClick={() => this.handleOk()} disabled={disabled} loading={this.state.isSaving}>保存</Button>
              </Col>
            </Row>
              </TabPane> */}
            <TabPane tab="导入提示信息" key="3">
              <Row style={{ marginTop: '20px' }}>
                <Col span={24}>
                  <Form.Item>
                    <TextArea rows={10} style={{ width: "100%" }} value={this.state.messages} disabled={true} />
                  </Form.Item>
                </Col>
              </Row>
            </TabPane>
          </Tabs>


        </Form>
      </div>
    );
  }

}

ImportPage.propTypes = {
};

export default connect(({ login, loading, custom, app }) => ({ login, loading, custom, app }))(Form.create()(ImportPage));
