import React, { Component } from 'react';
import { SplitPane, Button, AmosAlert, Collapse, CardPane } from 'amos-framework';
import { browserHistory } from 'amos-react-router';
import PropTypes from 'prop-types';
import PointBasicInfoxq from './PointBasicInfoxq';
import PointInputItemInfoxq from './PointInputItemInfoxq';
import PointCatalogInfoxq from './PointCatalogInfoxq';
import { updatePointAction, queryPointInputItemAction, queryPointClassifyWithInputItemAction, queryPointByIdAction } from '../../../services/pointService';
import { queryInputItemByConditionAction1 } from '../../../services/checkService';
import PointQRCode from './PointQRCode';
import HasPermission from '../../component/toolbar/hasPermission';

const Panel = Collapse.Panel;
const LevelEnum = { '1': '1级', '2': '2级', '3': '3级', '4': '4级', '5': '5级' };

class PointInfoEditxq extends Component {
  constructor(props) {
    super(props);

    this.state = {
      basicInfoFormData: {},
      pointInputItemData: [],
      catalogInputItemData: [],
      pointPhotoData: [],
      basicInfoFom: {},
      catalogWithInputItem: {},
      pointQRInfo: {},
      activeKey: '1',
      inputItemData: []
    };

    this.onBasicInfoFormChange = this.onBasicInfoFormChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleCancel = this.handleCancel.bind(this);
  }

  componentWillMount() {
    const { pointId } = (this.props.location || {}).state || {};

    pointId &&
      queryPointInputItemAction(pointId).then(data => {
        let tempInputItem = [];
        for (let i = 0; i < data.length; i++) {
          data[i].orderNo = data[i].pOrderNo;
          tempInputItem.push(data[i]);
        }

        this.setState({
          pointInputItemData: tempInputItem
        });
      });

    pointId &&
      queryPointClassifyWithInputItemAction(pointId).then(data => {
        let { catalogInputItemData } = this.state;
        for (let name in data) {
          let tempData = {};
          let tempNameData = data[name].pointInputItemVo;
          let inputNameData = [];
          let inputIdData = [];
          let pItemIdsMap = [];
          tempData.name = name.slice(0, name.lastIndexOf('*'));
          for (let i = 0; i < tempNameData.length; i++) {
            // 巡检项名称后添加等级
            let _name = tempNameData[i].name;
            _name = tempNameData[i].level ? _name + '(' + LevelEnum[tempNameData[i].level] + ')' : _name;
            inputNameData.push(_name);
            inputIdData.push(tempNameData[i].id);
            let inputItemId = tempNameData[i].id;
            let pointItemId = tempNameData[i].pointItemId;
            let pItemIdMap = {};
            pItemIdMap[inputItemId] = pointItemId;
            pItemIdsMap.push(pItemIdMap);
          }
          tempData.inputItemName = inputNameData.join();
          tempData.orderNo = Number(name.slice(name.lastIndexOf('*') + 1, name.length));
          tempData.inputItemId = inputIdData;
          tempData.id = data[name].id;
          tempData.pItemIdsMap = pItemIdsMap;
          tempData.pointInputItemVo = tempNameData;
          catalogInputItemData[tempData.orderNo] = tempData;
        }
        // queryInputItemByConditionAction().then(data => {
        //   this.setState({ inputItemData: data });
        // });
        this.queryInputItem();
        this.setState({
          catalogWithInputItem: data,
          catalogInputItemData
        });
      });

    // 根据ID查询点信息
    pointId && queryPointByIdAction(pointId).then(data => {
      let { pointQRInfo } = this.state;
      
      pointQRInfo.pointNo = data.pointNo;
      pointQRInfo.pointName = data.name;
      this.setState({
        pointQRInfo
      });
    });
  }

  onInputItemTableValueChange = values => {
    this.setState({ pointInputItemData: values });
  };

  onCatalogTableValueChange = values => {
    this.setState({ catalogInputItemData: values });
  };

  onBasicInfoFormChange(data, form) {
    this.setState({ basicInfoFormData: data });
    this.setState({ basicInfoFom: form });
  }

  onPanelChange(key) {
    if (Array.isArray(key)) {
      this.setState({
        activeKey: key[0]
      });
    }
  }

  // resizeBind = () => {
  //   this.forceUpdate();
  // }
  queryInputItem = (searchParams) => {
    let params = new Array();
    if (searchParams) {
      params.push(searchParams);
    }
    queryInputItemByConditionAction1(params).then(data => {
      this.setState({ inputItemData: data });
    });
  }

  handleSubmit() {
    let { pointInputItemData, catalogInputItemData } = this.state;
    let basicInfoForm = this.pointBasicInfo.form;
    let basicInfoFormData = basicInfoForm.props.model;
    basicInfoForm.validate((valid, dataValues) => {
      if (valid) {
        let catalogs = new Object();
        catalogInputItemData.map((value) => {
          catalogs[value.name] = value ;
          return value.name;
        });
        let keys = Object.keys(catalogs);
        if (keys.length < catalogInputItemData.length) {
          AmosAlert.error('错误', '扩展分类名重复！！！');
          return false;
        }
        let pointParam = this.preparePointParam(basicInfoFormData, pointInputItemData, catalogInputItemData);

        updatePointAction(pointParam).then(
          data => {
            AmosAlert.success('提示', '保存成功');
            browserHistory.goBack('/main/patrol/point');
          },
          error => {
            AmosAlert.error('错误', '保存失败');
          }
        );
      } else {
        console.log('error submit!!');
        return false;
      }
    });
  }

  preparePointParam(basicInfoFormData, pointInputItemData, catalogInputItemData) {
    let pointParam = Object();
    let point = Object();

    Object.assign(point, basicInfoFormData);
    this.pointCatalogInfo;
    pointParam.point = point;
    // if (pointParam.point.routeId !== '') {
    //   if (Array.isArray(pointParam.point.routeId)) {
    //     pointParam.point.routeId = pointParam.point.routeId.join();
    //     pointParam.point.routeName = pointParam.point.routeName.join();
    //   } else {
    //     let tempRouteIdData = [];
    //     let tempRouteNameData = [];
    //     let routeId = pointParam.point.routeId.split(',');
    //     let routeName = pointParam.point.routeName.split(',');
    //     for (let i = 0; i < routeId.length; i++) {
    //       if (routeId[i] !== '') {
    //         tempRouteIdData.push(parseInt(routeId[i]));
    //         tempRouteNameData.push(routeName[i]);
    //       }
    //     }
    //   }
    // }
    pointParam.pointPhotoList = [];

    pointParam.inputItemVoInfo = pointInputItemData;
    for (let i = 0; i < pointInputItemData.length; i++) {
      pointInputItemData[i].pOrderNo = pointInputItemData[i].orderNo;
    }

    pointParam.pointClassifyList = [];
    pointParam.classifyInputItemEditMap = {};
    for (let i = 0; i < catalogInputItemData.length; i++) {
      let catalogInputItem = catalogInputItemData[i];
      if (catalogInputItemData[i].name !== undefined) {
        let pointClassify = Object();
        pointClassify.name = catalogInputItem.name;
        pointClassify.orderNo = catalogInputItem.orderNo;
        pointClassify.id = catalogInputItem.id ? catalogInputItem.id : 0;
        pointParam.pointClassifyList.push(pointClassify);

        let catalogName = catalogInputItem.name;
        let catalogItemIds = catalogInputItem.inputItemId;
        let catalogItemList = [];

        // 根据选择的项更新分类-项map
        for (let j = 0; j < catalogItemIds.length; j++) {
          let r = pointInputItemData.findIndex(item => item.id === catalogItemIds[j]);
          if (r < 0) { // 未找到对应项
            catalogItemIds.splice(j, 1);
          }
        }

        // TODO
        let tempPItemIdsMap = [];
        for (let k = 0; k < catalogItemIds.length; k++) {
          let itemId = catalogItemIds[k];
          let pItemIdMap = {};
          if (undefined !== catalogInputItem.pItemIdsMap) {

            for (let m = 0; m < catalogInputItem.pItemIdsMap.length; m++) {
              if ( undefined === catalogInputItem.pItemIdsMap[m][itemId]) {
                pItemIdMap[itemId] = 0;  //表示新增
              }
              if (catalogInputItem.pItemIdsMap[m][itemId] > 0) {
                pItemIdMap[itemId] = catalogInputItem.pItemIdsMap[m][itemId];
                break;
              }
            }
            if (catalogInputItem.pItemIdsMap.length === 0) {
              pItemIdMap[itemId] = 0; //表示新增
            }
          }
          else {
            pItemIdMap[itemId] = 0; //表示新增
          }
          tempPItemIdsMap.push(pItemIdMap);
        }

        catalogInputItem.pItemIdsMap = tempPItemIdsMap;
        if (catalogInputItem.pItemIdsMap !== undefined) {
          for (let j = 0; j < catalogInputItem.pItemIdsMap.length; j++) {
            catalogItemList.push(catalogInputItem.pItemIdsMap[j]);
          }
        } else {  //新增分类项
          let pItemIdMap = {};
          pItemIdMap[catalogItemIds] = 0;
          catalogItemList.push(pItemIdMap);
        }

        pointParam.classifyInputItemEditMap[catalogName] = catalogItemList;
      }
    }

    return pointParam;
  }

  handleCancel = e => {
    browserHistory.goBack('/main/patrol/point');
  };

  render() {
    let { pointInputItemData, catalogWithInputItem, catalogInputItemData, pointQRInfo, activeKey, inputItemData } = this.state;
    const { pointId } = (this.props.location || {}).state || {};
    const _true_ = true;
    const edit = true;
    return (
      <SplitPane vertical secondaryDefaultSize={8} percentage={_true_}>
        <SplitPane mainPaneMinSize={50} secondaryDefaultSize={50} secondaryMinSize={50} percentage={_true_}>
          <CardPane title="基础信息"  style={{ height: '100%' }}>
            <div>
              <PointBasicInfoxq pointId={pointId}
                onBasicInfoFormChange={this.onBasicInfoFormChange}
                ref={pointBasicInfo => this.pointBasicInfo = pointBasicInfo}
              />
            </div>
          </CardPane>
          <div className="point-info-edit-right">
            <Collapse arrowAlign="right" activeKey={[activeKey]} accordion={_true_} onChange={key => this.onPanelChange(key)}>
              <Panel header="检查项目" key="1">
                <PointInputItemInfoxq inputItemData={inputItemData} pointInputItemData={pointInputItemData} onInputItemTableValueChange={this.onInputItemTableValueChange} edit={edit} queryInputItem={this.queryInputItem} />
              </Panel>
              <Panel header="扩展分类" key="2">
                <PointCatalogInfoxq
                  catalogWithInputItem={catalogWithInputItem}
                  catalogInputItemData={catalogInputItemData}
                  pointInputItemData={pointInputItemData}
                  onCatalogTableValueChange={this.onCatalogTableValueChange}
                  edit={edit}
                />
              </Panel>
              {/*<Panel header="图片说明" key="3">
                图片说明
              </Panel>*/}
              <Panel header="卫士码" key="4">
                <PointQRCode pointQRInfo={pointQRInfo} />
              </Panel>
            </Collapse>
          </div>
        </SplitPane>
        {/* <div className="point-info-footer" style={{ textAlign: 'center', marginTop: '1rem' }}>
          <HasPermission permissionCode='point'>
            <Button onClick={this.handleSubmit}>提交</Button>
          </HasPermission>
          <Button onClick={this.handleCancel}>返回</Button>
        </div> */}
      </SplitPane>
    );
  }
}

PointInfoEditxq.propTypes = {
  location: PropTypes.any
};
export default PointInfoEditxq;
