/* eslint-disable no-const-assign,prefer-destructuring */
/**
 * Created by mar105 on 2019-01-04.
 */
// , Switch, Icon
import React, { Component } from 'react';
import { Form } from '@ant-design/compatible';
// import '@ant-design/compatible/assets/index.css';
import { Layout, Spin, Tabs, Avatar, message, Select, Input, Button } from 'antd-v4';
import * as commonFunc from './../Common/commonFunc';/* 通用单据方法 */ /* 通用单据方法 */
import StaticEditTable from '../Common/CommonTable';/* 可编辑表格 */
import styles from './../../index.less';
import CommonView from './../Common/CommonView';
import CommonBase from './../Common/CommonBase';/* 获取配置及数据 */
import * as commonUtils from './../../utils/utils';/* 通用方法 */
import * as commonBusiness from './../Common/commonBusiness';/* 单据业务功能 */
import commonConfig from './../../utils/config';
import * as commonServices from './../../services/services';/*   服务类   */

const { TabPane } = Tabs;
const { Option } = Select;
const { Content } = Layout;

class AuditInformation extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }
  componentWillReceiveProps(nextProps) {
    const {
      formData, currentId, checkData, app,
    } = nextProps;
    let { masterConfig, canSendMsg } = nextProps;
    const { userinfo } = app;
    if (commonUtils.isEmptyArr(masterConfig) && formData.length > 0) {
      const sId = currentId || nextProps.masterData?.sId || '';
      /* 数据Id */
      masterConfig = formData.filter(item => !item.bGrd)[0];
      const checkConfig = formData.filter(item => item.bGrd && item.sTbName === 'sysbillcheckresult')[0];
      const checkColumn = commonFunc.getHeaderConfig(checkConfig);
      this.handleGetData(masterConfig, checkConfig);
      this.props.onSaveState({
        masterConfig, sId, pageLoading: false, checkConfig, checkColumn, checked: true, canSendMsg: false,
      });
    } else if (commonUtils.isNotEmptyArr(checkData) && (JSON.stringify(this.props.checkData) !== JSON.stringify(checkData))) {
      const iIndex = checkData.findIndex(item => item.sResult !== '1' && item.sResult !== '2' && item.sCheckPersonId === userinfo.sId);
      if (iIndex > -1) {
        canSendMsg = true;
      }
      this.props.onSaveState({ canSendMsg });
    }
  }

  shouldComponentUpdate(nextProps) {
    const { checkColumn, masterConfig } = nextProps;
    return commonUtils.isNotEmptyArr(checkColumn) || commonUtils.isNotEmptyObject(masterConfig);
  }
  /**   获取主表数据   */
  handleGetData = async (masterConfig, checkConfig) => {
    const { currentId } = this.props; /* 当前页签数据 */
    const sId = currentId || this.props.masterData?.sId || '';
    await this.props.handleGetDataOne({ name: 'master', configData: masterConfig, condition: { sId, pageSize: '', pageNum: '' } });
    const { masterData } = this.props;
    if (!commonUtils.isEmptyObject(checkConfig) && !commonUtils.isEmptyObject(masterData)) {
      this.props.handleGetDataSet({
        name: 'check', configData: checkConfig, condition: { sSqlCondition: { sBillId: masterData.sBillId } },
      });
    }
  };
  handleForm = (form) => {
    this.form = form;
  };
  handleSelectChange = (value) => {
    let iReply = 1;
    if (value === 'approve') {
      iReply = 1;
    } else if (value === 'refuse') {
      iReply = 0;
    }
    this.props.onSaveState({ iReply });
  };
  handleSwitchChange = (value) => {
    this.props.onSaveState({ checked: value });
  };
  handleSubmit = async () => {
    const {
      sModelsId, masterData, masterConfig, checkConfig,
    } = this.props;
    let { iReply } = this.props;
    const sReply = document.getElementById('sReply').value;
    iReply = commonUtils.isEmptyNumber(iReply) ? 1 : iReply;
    const url = `${commonConfig.server_host}business/getProData?sModelsId=${sModelsId}`;
    const value = {
      sProName: 'Sp_System_ReplyCheckMsg',
      paramsMap: {
        sMsgGuid: masterData.sId,
        sBillGuid: masterData.sBillId,
        iReply,
        sReply,
      },
    };
    const returnData = (await commonServices.postValueService(this.props.app.token, value, url)).data;
    if (returnData.code === 1) {
      if (returnData.dataset.rows[0].dataSet.outData[0].sCode === 1) {
        this.handleGetData(masterConfig, checkConfig);
        message.success(returnData.msg);
      } else {
        message.error(returnData.dataset.rows[0].dataSet.outData[0].sReturn);
      }
    } else { /*   失败   */
      this.props.getServiceError(returnData);
    }
  };
  render() {
    const { masterData, sModelsType, app } = this.props;
    const imgSrc = commonBusiness.handleAddIcon(masterData, sModelsType, app);
    return (
      <Spin spinning={pageLoading}>
        <WorkOrderComponent
          {...this.props}
          {...this.state}
          onReturnForm={this.handleForm}
          onSelectChange={this.handleSelectChange}
          onSwitchChange={this.handleSwitchChange}
          onSubmit={this.handleSubmit}
          imgSrc={imgSrc}
        />
      </Spin>
    );
  }
}

const WorkOrderComponent = Form.create({
  mapPropsToFields(props) {
    const { masterData } = props;
    const obj = commonFunc.mapPropsToFields(masterData, Form);
    return obj;
  },
})((props) => {
  const {
    form, onReturnForm, onSelectChange, onSubmit, checked,
  } = props;
  /*   回带表单   */
  onReturnForm(form);
  const propsType = {
    ...props,
    onChange: props.onMasterChange,
  };
  const style = checked ? 'block' : 'none';
  /*
 <div style={{ padding: '10px 12px' }}>显示审核记录: &nbsp;
   <Switch
     checkedChildren={<Icon type="check" />}
     unCheckedChildren={<Icon type="close" />}
     onChange={onSwitchChange}
   />
 </div>
 */
  return (
    <Form>
      <Layout>
        <Layout id="AudiInfomation" className={styles.clayout} style={{ padding: '90px 0 0 0' }}>
          <Content className={styles.content} >
            <div className="bill-search-group" >
              <CommonView {...propsType} />
            </div>
            <div id="slaveTabs" className={styles.bShow} style={{ overflow: 'auto', display: style }}>
              <div>
                <Avatar src={props.imgSrc} />
              </div>
              <Tabs tabBarStyle={{ paddingLeft: '10px' }} >
                <TabPane tab="审批信息" key={3} >
                  <StaticEditTable {...commonBusiness.getTableTypes('check', props)} footer="hidden" />
                </TabPane>
              </Tabs>
            </div>
            { props.canSendMsg ? (
              <div style={{ paddingLeft: '13px', width: '30%' }}>
                <span style={{ height: '40px', lineHeight: '40px' }}>回答内容:</span>
                <Select defaultValue="approve" onChange={onSelectChange}>
                  <Option value="approve">批准</Option>
                  <Option value="refuse">拒绝</Option>
                </Select>
              </div>) : ''
            }
            { props.canSendMsg ? (<Input id="sReply" addonBefore="备注:" style={{ paddingLeft: '13px', width: '30%' }} />) : ''}
            { props.canSendMsg ? (
              <div style={{ marginTop: '8px', paddingLeft: '13px' }}>
                <Button type="primary" htmlType="submit" onClick={onSubmit}>发送</Button>
              </div>) : ''}
          </Content>
        </Layout>
      </Layout>
    </Form>
  );
});

export default CommonBase(AuditInformation);
