import React, { Component } from 'react';
import { withRouter } from 'dva/router';
import {
  Modal,
  message
} from "antd";
import SetLocation from '../CreateTask/SetLocation';
import bcx_utils from '../../../common/bcx_utils';
import {
  taskGetStepTwoDetail,
  taskDeleteAddress
} from '../../../services/api';
import { addComTaskAttendAddress } from '../../../services/api_taskbuild';
@withRouter
export default class Uninsured extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      dataSource: {
        attendType: ''
      },
      gdbzDataSource: {
        //固定班制 详情
        returnComTaskFixedDList: [
          {
            "weekDay": 1,
            "shiftDetails": "休息",
            "shiftId": "-1",
            "taskFixedId": ""
          },
          {
            "weekDay": 2,
            "shiftDetails": "休息",
            "shiftId": "-1",
            "taskFixedId": ""
          },
          {
            "weekDay": 3,
            "shiftDetails": "休息",
            "shiftId": "-1",
            "taskFixedId": ""
          },
          {
            "weekDay": 4,
            "shiftDetails": "休息",
            "shiftId": "-1",
            "taskFixedId": ""
          },
          {
            "weekDay": 5,
            "shiftDetails": "休息",
            "shiftId": "-1",
            "taskFixedId": ""
          },
          {
            "weekDay": 6,
            "shiftDetails": "休息",
            "shiftId": "-1",
            "taskFixedId": ""
          },
          {
            "weekDay": 7,
            "shiftDetails": "休息",
            "shiftId": "-1",
            "taskFixedId": ""
          }
        ], //默认休息 初始化值
        returnComTaskAttendAddressList: []
      },
      //排班制
      pbzDataSource: {
        comShifts: [], //出勤班次
        returnComTaskSchedulCycleList: [], //周期设置
        returnComTaskAttendAddressList: [] //地址列表
      },
      //排班制 缓存
      pbzDataSourceCache: {
        comShifts: [],
        returnComTaskSchedulCycleList: [],
        returnComTaskAttendAddressList: []
      },
      addressRange: '300', //出勤范围
    }
  }


  componentWillReceiveProps(props) {
    const { comTaskId, visible } = props;
    if (comTaskId && visible) {
      taskGetStepTwoDetail({ comTaskId }).then(({ data }) => {
        if (!data) {
          throw "数据异常";
        }
        this.setState({
          dataSource: data
        });
        const { PBZ, GDBZ } = data;
        if (PBZ && PBZ !== '') {
          this.setState({
            pbzDataSource: PBZ,
            pbzDataSourceCache: JSON.parse(JSON.stringify(PBZ))
          });
          if (
            PBZ.returnComTaskAttendAddressList &&
            PBZ.returnComTaskAttendAddressList.length
          ) {
            this.setState({
              addressRange: PBZ.returnComTaskAttendAddressList[0].addressRange
            });
          }
        }
        if (GDBZ && GDBZ !== '') {
          this.setState({ gdbzDataSource: GDBZ });
          if (
            GDBZ.returnComTaskAttendAddressList &&
            GDBZ.returnComTaskAttendAddressList.length
          ) {
            this.setState({
              addressRange: GDBZ.returnComTaskAttendAddressList[0].addressRange
            });
          }
        }
      }, (err) => {
        console.log(err);
      });
    }
  }
  componentDidMount() {

  }
  //增加出勤地点
  _addArea = (type, [addressLongitude, addressLatitude], address) => {
    const target = this.state[type];
    const { addressRange } = this.state;
    let selectedAddress = target.returnComTaskAttendAddressList.filter(
      item => item.address === address
    );
    if (selectedAddress.length) {
      message.warning('该地点已被选为出勤地点，请勿重复选择');
      return;
    }
    target.returnComTaskAttendAddressList.push({
      taskAttendAddressId: '',
      address,
      addressLongitude,
      addressLatitude,
      addressRange,
      key: ''
    });
    target.returnComTaskAttendAddressList = target.returnComTaskAttendAddressList.map(
      (val, i) => {
        val.key = i;
        return val;
      }
    );
    const { comTaskId } = this.props;
    addComTaskAttendAddress({
      addressLongitude,
      addressLatitude,
      address,
      comTaskId,
      addressRange
    }).then(() => {
      this.props.updateTable && this.props.updateTable();
      this.setState({ [type]: target });
    });
  };
  //删除出勤地点
  _deleteLocalItem = (cursor, { taskAttendAddressId, address }) => {
    
    const { attendType = '2' } = this.state.dataSource;
    let length = 0;
    if(attendType == 1) {
      const gdbzDataSource = bcx_utils.jsoncopy(this.state.gdbzDataSource);
      const returnComTaskAttendAddressList = gdbzDataSource.returnComTaskAttendAddressList;
      length = returnComTaskAttendAddressList.length;
    }else {
      const pbzDataSource = bcx_utils.jsoncopy(this.state.pbzDataSource);
      const returnComTaskAttendAddressList = pbzDataSource.returnComTaskAttendAddressList;
      length = returnComTaskAttendAddressList.length;
    }

    if(length <= 1) {
      return Modal.error({
        title: '至少保留一个地址',
        okText: '确定',
      });
    }

    //本地数据删除方法
    const filterDelete = (data, list) => {
      //固定班制
      if (attendType == '1') {
        const gdbzDataSource = bcx_utils.jsoncopy(this.state.gdbzDataSource);
        const returnComTaskAttendAddressList = gdbzDataSource.returnComTaskAttendAddressList;
        gdbzDataSource.returnComTaskAttendAddressList = returnComTaskAttendAddressList.filter(
          val => val.address !== address
        );
        this.setState({
          gdbzDataSource
        });
      }
      //排班制
      if (attendType == '2') {
        const pbzDataSource = bcx_utils.jsoncopy(this.state.pbzDataSource);
        const returnComTaskAttendAddressList = pbzDataSource.returnComTaskAttendAddressList;
        pbzDataSource.returnComTaskAttendAddressList = returnComTaskAttendAddressList.filter(
          // val => val.taskAttendAddressId !== taskAttendAddressId
          val => val.address !== address
        );
        this.setState({
          pbzDataSource
        });
      }
    };
    //删除确认框
    Modal.confirm({
      title: '确认删除?',
      okText: '确定',
      cancelText: '取消',
      onOk:() => {
        taskDeleteAddress({taskAttendAddressId}).then(res => {
          this.props.updateTable && this.props.updateTable();
          filterDelete();
        });
      },
      onCancel() {
        console.log('Cancel');
      }
    });
  };
  render() {
    const { attendType } = this.state.dataSource;
    return (
      <Modal
        title={`${this.props.taskName}-考勤点管理`}
        // visible={!!this.props.comTaskId}
        visible={this.props.visible}
        footer={null}
        width="1000px"
        onCancel={this.props.onCancel}
      >
        {/*固定班次-设置地点*/}
        {attendType === '1' && (
          <SetLocation
            upper={true}
            dataSource={
              this.state.gdbzDataSource.returnComTaskAttendAddressList
            }
            text1={'添加新考勤点'}
            text2={'已添加考勤点'}
            deleteLocalItem={this._deleteLocalItem}
            addArea={this._addArea.bind(this, 'gdbzDataSource')}
            addressRangeChange={addressRange => { this.setState({ addressRange }) }}
            addressRange={this.state.addressRange}
            taskCityName={this.state.dataSource.taskCityName} //添加当前驻勤城市名称，9-28
          />
        )}

        {/*排班次-设置地点*/}
        {attendType === '2' && (
          <SetLocation
            text1={'添加新考勤点'}
            text2={'已添加考勤点'}
            disabled={this.props.taskStatusValue == 2 || this.props.taskStatusValue == 7}
            upper={true}
            dataSource={
              this.state.pbzDataSource.returnComTaskAttendAddressList
            }
            deleteLocalItem={this._deleteLocalItem}
            addArea={this._addArea.bind(this, 'pbzDataSource')}
            addressRangeChange={addressRange => { this.setState({ addressRange }) }}
            addressRange={this.state.addressRange}
            taskCityName={this.state.dataSource.taskCityName} //添加当前驻勤城市名称，9-28
          />
        )}
      </Modal>
    );
  }
}
