
import React, { Component } from "react";
import st from "styled-components";
import {
  Input,
  Row,
  Col,
  Radio,
  Button,
  Form,
  DatePicker,
  Select,
  Table,
  message
} from "antd";
import PSelect from '../../../../components/Pro/PSelect';
import PCascader from '../../../../components/Pro/PCascader';
import RegulatorCascader from '../../../../components/RegulatorCascader';
import bcx_utils from '../../../../common/bcx_utils';
import SelectContractModal from './SelectContractModal.jsx';
import AddShareTask from './AddShareTask';
import TaskInfoColumns1 from './TaskInfoColumns1';
import TaskInfoColumns2 from './TaskInfoColumns2';
import ActivityList from './ActivityList';
import moment from 'moment';
import { getTempTaskDetail, getActivityList } from '../../../../services/api';
import PMapMarker from '../../../../components/Pro/PMapMarker';
import './index.less';
const { RangePicker } = DatePicker;
const { Option } = Select;
const dateFormat = 'YYYY-MM-DD';
const formItemLayout = {
  labelCol: {
    span: 8
  },
  wrapperCol: {
    span: 16
  },
  labelAlign: 'right'
};
const formItemLayout1 = {
  labelCol: {
    span: 4
  },
  wrapperCol: {
    span: 20
  },
  labelAlign: 'right'
};
const formItemLayout2 = {
  labelCol: {
    span: 0
  },
  wrapperCol: {
    span: 24
  },
  labelAlign: 'right'
};
const formItemLayout4 = {
  labelCol: {
    span: 10
  },
  wrapperCol: {
    span: 14
  },
  labelAlign: 'right'
};
@Form.create()
export default class TaskInfo extends Component {
  constructor(props) {
    super(props);
    this.state = {
      map: "",//地图
      province: "",//省
      place: "",//地点
      searchResult: "",//地图搜索结果
      showInitialMarker: false,
      param: {
        addressLongitude: null,
        addressLatitude: null
      },
      contractModalVisble: false,
      comContractList: [],//关联的合同数据
      shareTaskVisble: false,
      shareTaskList: [],//关联的共享任务
      taskId: this.props.taskId || null,
      detailData: null,//详情数据（如果是编辑页面，需要先掉详情接口）
      activeDataList: []
    }
  }
  componentWillReceiveProps(nextProps) {
  }
  componentDidMount() {
    console.log(this.props)
    this.__loadMapScript();
    this.props.onGetForm && this.props.onGetForm(this.props.form);
    if (this.props.taskId) {
      this._getTempTaskDetail(this.props.taskId)
    }
    // 该接口存在问题，目前无法调用，先注释
    // this._getActivityList()
  }
  __loadMapScript = () => {
    const script = document.createElement("script");
    script.src =
      "http://webapi.amap.com/maps?v=1.4.4&key=9066916e054aa3083a6f081a2a9f9d7a";
    document.body.appendChild(script);

    const script2 = document.createElement("script");
    script2.src =
      "http://cache.amap.com/lbs/static/addToolbar.js";
    if (!"AMap" in window) {
      document.body.appendChild(script2);
    }

    this._loading();
  };
  _loading = () => {
    let _this = this;

    function nextStep() {
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve("AMap" in window);
        }, 500);
      });
    }

    async function ajaxMap() {
      let ifComplete = false;
      for (var i = 0; i < 10; i++) {
        if (!ifComplete) {
          ifComplete = await nextStep();
        } else {
          if (ifComplete) {
            // console.log("地图初始化中。。。");
            (_this.state.param && _this.state.param.addressLongitude != '' && _this.state.param.addressLatitude != '') ?
              _this._initialMap(_this.state.param.addressLongitude, _this.state.param.addressLatitude) :
              _this._initialMap();
          } else {
            message.error("网络超时")
          }
        }
      }
    }

    ajaxMap();
  }
  _initialMap = (lng, lat) => {
    const that = this;
    const { AMap } = window;

    let config = {
      resizeEnable: true,
      zoom: 14,
    };
    if (lng && lat) {
      config = { ...config, ...{ center: [lng, lat] } }
    }
    var map = new AMap.Map('temporary_map', config);
    this.setState({ map });
    //是否显示初始化的标注
    let showInitialMarker = that.state.showInitialMarker;
    if (showInitialMarker) {
      let marker = new AMap.Marker({
        icon: "http://webapi.amap.com/theme/v1.3/markers/n/mark_r.png",
        position: [lng, lat]
      });
      marker.setMap(map);
    }
  }
  _searchMap = () => {
    this.setState({ showInitialMarker: false });
    const { AMap } = window;
    const that = this;
    let place = this.state.place;
    let province = this.state.province;
    let map = this.state.map;
    AMap.service('AMap.PlaceSearch', function () {//回调函数
      //实例化PlaceSearch
      let placeSearch = new AMap.PlaceSearch();
      //TODO: 使用placeSearch对象调用关键字搜索的功能
      placeSearch.search(place, function (status, result) {
        if (status == 'no_data' || result.poiList.pois.length == 0) {
          bcx_utils.preventRepeatAsync((callback) => callback((resolve) => {
            message.warning(`当前搜索地址暂无记录`, 1.5, () => {
              window.setTimeout(() => {
                resolve();
              }, 500);
            });
          }))
          return;
        }
        let searchResult = result.poiList.pois;
        let searchResultTmp = searchResult;
        //查看是否有完全符合的结果
        searchResult.map((item, index) => {
          if (place === item.name) {
            searchResult = [];
            searchResult.push(item)
          }
        });
        let lng = searchResult[0].location.lng;
        let lat = searchResult[0].location.lat;

        //将第一个结果放在input里或者是完全匹配的结果
        const { setFieldsValue } = that.props.form;
        let param = that.state.param;
        param.addressLongitude = searchResult[0].location.lng;
        param.addressLatitude = searchResult[0].location.lat;
        that.setState({ param });
        that.setState({ markers: [] })
        that.setState({ place: searchResult[0].name });
        setFieldsValue({ taskAddress: province + searchResult[0].name });
        that._initialMap(lng, lat);
        that.setState({ searchResult });

        searchResult.map((item, index) => {
          let lng = item.location.lng;
          let lat = item.location.lat;
          that.addMarker(lng, lat, index);
        });
      });
    })
  }
  handleKeyUp = (e) => {
    // e.preventDefault();
    // if (!this.state.province) {
    //   bcx_utils.preventRepeatAsync((callback) => callback((resolve) => {
    //     message.warning(`请先选择省市区`, 1.5, () => {
    //       window.setTimeout(() => {
    //         resolve();
    //       }, 500);
    //     });
    //   }))
    // } else {
      this.setState({ showInitialMarker: false }, () => {
        this._initialMap();
        this._searchMap()
      });
    // }
  }
  handleInputSearch = (e) => {
    const { value } = e.target;
    const province = this.state.province;
    this.setState({ place: value });
    //不可删除
    if (value.length < province.length) {
      e.target.value = province;
    }
    if (!value.includes(province)) {
      e.target.value = province;
    }
  }
  addMarker = (lng, lat, index) => {
    let searchResult = this.state.searchResult;
    let map = this.state.map;
    let markers = this.state.markers;
    let province = this.state.province;
    let that = this;
    let marker = new AMap.Marker({
      icon: "http://webapi.amap.com/theme/v1.3/markers/n/mark_b.png",
      position: [lng, lat]
    });
    markers.push(marker);
    marker.setMap(map);
    if (index) {
      marker.on('click', function () {
        // console.log('您点击了点', searchResult[index].name, searchResult[index].location.lng, searchResult[index].location.lat);
        let param = that.state.param;
        param.addressLongitude = searchResult[index].location.lng;
        param.addressLatitude = searchResult[index].location.lat;
        that.setState({ param, place: searchResult[index].name });
        const { setFieldsValue } = that.props.form;
        setFieldsValue({ taskAddress: searchResult[index].name });
        setFieldsValue({ longitudeAndLatitude: [searchResult[index].location.lng, searchResult[index].location.lat] });
      });
    }
  }
  _getTempTaskDetail(comTempTaskId) {
    getTempTaskDetail({ comTempTaskId }).then(res => {
      if (res.retType === '0') {
        this.setState({
          detailData: res.data,
          shareTaskList: res.data.shareComList || [],
          comContractList: [res.data.comContractInfo],
          param: {
            addressLongitude: res.data.addressLongitude,
            addressLatitude: res.data.addressLatitude,
          },
          place: res.data.taskAddress,
          showInitialMarker: true
        })
      }
    })
  }
  //必选框的标致
  mustLabel() {
    return (
      <span style={{ color: 'red' }}>*</span>
    )
  }
  //关联合同中的移除合同
  removeContract() {
    const { setFieldsValue } = this.props.form;
    this.setState({
      comContractList: []
    });
    setFieldsValue({
      comContractList: []
    });
  }
  //删除任务
  removeTask(selectedTaskRows) {
    const { setFieldsValue } = this.props.form;
    const data = this.state.shareTaskList.filter(item => {
      if (!selectedTaskRows.includes(item)) {
        return item
      }
    })
    this.setState({
      shareTaskList: data
    })
    if (data.length == 0) {
      setFieldsValue({ shareTaskList: [] })
    }
  }
  //获取活动列表
  _getActivityList() {
    getActivityList().then(res => {
      if (res.retType == '0') {
        this.setState({
          activeDataList: res.data
        })
      }
    })
  }
  render() {
    const { detailData } = this.state;
    const { getFieldDecorator, getFieldValue, setFieldsValue } = this.props.form;
    const columns1 = TaskInfoColumns1.call(this);
    const columns2 = TaskInfoColumns2.call(this);
    return (
      <div>
        <Form layout="horizontal" style={{ paddingRight: 30 }}>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item {...formItemLayout} label="任务名称">
                {getFieldDecorator('taskName', {
                  initialValue: detailData ? detailData.taskName : '',
                  rules: [{ required: true, message: '请输入任务名称' }],
                })(<Input style={{ width: '100%' }} maxLength={30} style={{ width: '100%' }} placeholder="请输入任务名称" disabled={this.props.readOnly} />)}
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item {...formItemLayout} label="驻勤点类型">
                {getFieldDecorator('taskStationType', {
                  initialValue: detailData ? detailData.taskStationType : [],
                  rules: [{ required: true, message: '请选择驻勤点类型' }],
                })(<PSelect placeholder="请选择驻勤点类型" deleteAll style={{ width: '100%' }} type="taskStationType" disabled={this.props.readOnly} />)}
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item {...formItemLayout} label="监管机构">
                {getFieldDecorator('cityOrg', {
                  initialValue: detailData ? [
                    detailData.cityOrgId,
                    detailData.districtOrgId,
                    detailData.policeStationId
                  ] : [],
                  rules: [{ required: true, message: '请选择监管机构' }],
                })(<RegulatorCascader style={{ width: '100%' }} disabled={this.props.readOnly} />)}
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item {...formItemLayout} label="服务对象名称">
                {getFieldDecorator('serviceObject', {
                  initialValue: detailData ? detailData.serviceObject : '',
                  rules: [{ required: true, message: '请输入服务对象名称' }],
                })(<Input style={{ width: '100%' }} maxLength={30} placeholder="请输入服务对象名称" disabled={this.props.readOnly} />)}
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={24}>
              <Form.Item {...formItemLayout1} label="服务对象类型">
                {getFieldDecorator('serviceObjectType', {
                  initialValue: detailData ? detailData.serviceObjectType : [],
                  rules: [{ required: true, message: '请选择服务对象类型' }],
                })(<PSelect placeholder="请选择服务对象类型" style={{ width: '100%' }} type="serviceObjectType" disabled={this.props.readOnly} />)}
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}> <Col span={12}>
            <Form.Item {...formItemLayout} label="服务对象涉外情况">
              {getFieldDecorator('serviceObjectSySituation', {
                initialValue: detailData ? detailData.serviceObjectSySituation : [],
                rules: [{ required: true, message: '请选择服务对象涉外情况' }],
              })(<PSelect placeholder="请选择服务对象涉外情况" style={{ width: '100%' }} type="serviceObjectSySituation" disabled={this.props.readOnly} />)}
            </Form.Item>
          </Col>
            <Col span={12}>
              <Form.Item {...formItemLayout4} label="是否治安保卫重点单位">
                {getFieldDecorator('isSecurityImportantUnit', {
                  initialValue: detailData ? detailData.isSecurityImportantUnit : [],
                  rules: [{ required: true, message: '请选择是否治安保卫重点单位' }],
                })(
                  <Select style={{ width: '100%' }} placeholder="请选择" disabled={this.props.readOnly}>
                    <Option value="0">否</Option>
                    <Option value="1">是</Option>
                  </Select>
                )}
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={24}>
              <Form.Item {...formItemLayout1} label="任务内容">
                {getFieldDecorator('taskContent', {
                  initialValue: detailData ? detailData.taskContent : '',
                  rules: [{ required: true, message: '请输入任务内容' }],
                })(<Input.TextArea style={{ width: '100%' }} maxLength={200} rows={3} placeholder="请输入任务内容" disabled={this.props.readOnly} />)}
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={4} style={{ textAlign: 'right', lineHeight: '40px' }}>
              {this.mustLabel()}是否关联活动:
          </Col>
            <Col span={20} className='guanlian'>
              <Form.Item {...formItemLayout2} colon={false} label="" extra={<span style={{ color: '#F59A23', marginTop: '5px' }}>注：若活动承办方要求您发布的临保任务关联相应活动信息，请准确选择对应活动。</span>}>
                {getFieldDecorator('isRelationActivity', {
                  initialValue: detailData ? detailData.isRelationActivity : '0',
                  rules: [{ required: true, message: '请输选择' }],
                })(
                  <Radio.Group disabled={this.props.readOnly}>
                    <Radio value='0'>否</Radio>
                    <Radio value='1'>是</Radio>
                  </Radio.Group>
                )}
                {
                  getFieldValue('isRelationActivity') === '1' && <RodioSelector>
                    <Form.Item {...formItemLayout1} label="" colon={false}>
                      {getFieldDecorator('activityNo', {
                        initialValue: detailData ? 
                          this.props.readOnly ? 
                            detailData.activityCom + '-' + detailData.activityName + '-' + detailData.activityNo :
                            JSON.stringify({ sponsor: detailData.activityCom, fullName: detailData.activityName, activityNo: detailData.activityNo }) : [],
                        rules: [{ required: true, message: '请选择关联的活动' }],
                      })(
                        <Select style={{ width: 400 }} placeholder="请选择" disabled={this.props.readOnly}>
                          {
                            this.state.activeDataList.map((val, index) => {
                              return (
                                <Option value={JSON.stringify(val)} key={val.activityNo}> {val.activityNo}-{val.fullName}-{val.sponsor}</Option>
                              )
                            })
                          }
                        </Select>
                        // <ActivityList disabled={this.props.readOnly} />
                        // <PSelect placeholder="请选择关联的活动" style={{ width: 300 }} type="serviceObjectSySituation" />
                      )}
                    </Form.Item>
                  </RodioSelector>
                }
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={4} style={{ textAlign: 'right', lineHeight: '40px' }}>
              {this.mustLabel()}是否共享任务:
            </Col>
            <Col span={20}>
              <Form.Item {...formItemLayout2} colon={false} label="" extra={<span style={{ color: '#F59A23' }}>注：若您需要共享此任务给其他保安服务公司，可选中“是”，并选择相应共享的保安公司；被共享的保安公司在其共保任务列表可查看本任务并增减其企业保安员。</span>}>
                {getFieldDecorator('isShareTask', {
                  initialValue: detailData ? detailData.isShareTask : '0',
                  rules: [{ required: true, message: '请输选择' }],
                })(
                  <Radio.Group disabled={this.props.readOnly}>
                    <Radio value='0'>否</Radio>
                    <Radio value='1'>是</Radio>
                  </Radio.Group>
                )}
              </Form.Item>
            </Col>
          </Row>
          {
            getFieldValue('isShareTask') === '1' &&
            <Row gutter={16}>
              <Col span={20} offset={4}>
                {
                  !this.props.readOnly && <Form.Item {...formItemLayout2} colon={false} label="" >
                    {getFieldDecorator('shareTaskList', {
                      initialValue: this.state.shareTaskList,
                      rules: [{ required: true, message: '请添加共享任务' }],
                    })(<Btns>
                      <Button type="primary" size="small" onClick={() => {
                        this.setState({
                          shareTaskVisble: true
                        })
                      }}>添加</Button>
                      <Button type="danger" size="small" onClick={() => {
                        if (this.state.selectedTaskRows.length == 0) {
                          return Modal.warning({
                            title: '请先选择'
                          })
                        } else {
                          this.removeTask(this.state.selectedTaskRows)
                        }
                      }}>删除</Button>
                    </Btns>
                    )}
                  </Form.Item>
                }

                <TableContainer>
                  <Table
                    dataSource={this.state.shareTaskList}
                    columns={columns1}
                    rowSelection={{
                      onChange: (selectedRowKeys, selectedRows) => {
                        this.setState({
                          selectedTaskRows: selectedRows,
                          // selectedRowTaskKeys
                        });
                      },
                    }}
                  />
                </TableContainer>
              </Col>
            </Row>
          }

          {
            !this.props.readOnly && <Row gutter={16}>
              <Col span={4} style={{ textAlign: 'right', lineHeight: '40px' }}>
                {this.mustLabel()}关联合同:
            </Col>
              <Col span={20}>
                <Form.Item {...formItemLayout2} colon={false} label="">
                  {getFieldDecorator('comContractList', {
                    initialValue: this.state.comContractList,
                    rules: [{ required: true, message: '请关联该任务相应的合同' }],
                  })(
                    <Btns>
                      <Button type="primary" size="small" onClick={() => {
                        this.setState({
                          contractModalVisble: true,
                        });
                      }}>关联合同</Button>
                    </Btns>
                  )}
                </Form.Item>
                <TableContainer>
                  <Table
                    style={{ margin: '20px auto' }}
                    columns={columns2}
                    dataSource={this.state.comContractList}
                    scroll={{ x: '1500px' }}
                  />
                </TableContainer>
              </Col>
            </Row>
          }

          <Row gutter={16}>
            <Col span={20} offset={4}>
              <em style={{ color: '#F59A23', marginLeft: 15, fontSize: 14, display: 'block', textAlign: 'left' }}>注：任务地区、详细地址、任务时间发布后将不能修改，请注意填写。</em>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item {...formItemLayout} label="任务地区">
                {getFieldDecorator('taskLocation', {
                  initialValue: detailData ? [detailData.province, detailData.city, detailData.area] : '',
                  rules: [{ required: true, message: '请选择任务地区' }],
                })(
                  <PCascader
                    style={{ width: '100%' }}
                    onChange={(value, array) => {
                      let place = '';
                      array.map((item, index) => {
                        const { label } = item;
                        place += label;
                      });
                      const { setFieldsValue } = this.props.form;
                      this.setState({ province: place });
                      this.setState({ place });
                      setFieldsValue({ taskAddress: place });
                      setFieldsValue({ longitudeAndLatitude: [] });
                    }}
                    addressChange={(address) => {
                      this.setState({ province: address });
                    }}
                    placeholder="请选择"
                    disabled={this.props.readOnly}
                  />
                )}
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item {...formItemLayout} label="详细地址">
                {getFieldDecorator('taskAddress', {
                  initialValue: detailData ? detailData.taskAddress : '',
                  rules: [{ required: true, message: '请输入详细地址' }],
                })(
                  <Input.Search
                    enterButton
                    placeholder="请输入详细地址"
                    style={{ width: '100%' }}
                    disabled={this.props.readOnly}
                    onSearch={this.handleKeyUp}
                    onPressEnter={this.handleKeyUp}
                    onChange={this.handleInputSearch}
                    maxLength={100}
                  />
                )}
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={24} offset={4}>
              <Form.Item {...formItemLayout1} label="">
                {getFieldDecorator('longitudeAndLatitude', {
                  initialValue: detailData ? [detailData.addressLongitude, detailData.addressLatitude] : '',
                  rules: [{ required: true, message: '请先点击搜索按钮或enter来搜索地点' }],
                })(
                  // <div style={{ width: '100%', height: 230, overflow: 'hidden' }}>
                  //   <div id="temporary_map" style={{ width: '100%', height: 250 }}></div>
                  // </div>
                  <PMapMarker
                    param={this.state.param}
                  // clickMarker={(value) => {
                  //   console.log(value)
                  // }}
                  />
                )}
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item {...formItemLayout} label="执行范围">
                {getFieldDecorator("execRange", {
                  initialValue: detailData ? detailData.execRange : '',
                  rules: [
                    {
                      required: true,
                      pattern: /^\d{0,10}$/,
                      message: "请输入少于10个数字"
                    }
                  ]
                })(<Input addonAfter="米" disabled={this.props.readOnly} placeholder='请输入执行范围' />)}
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item {...formItemLayout} label="任务时间">
                {getFieldDecorator('taskDate', {
                  initialValue: detailData ? [
                    moment(detailData.startDate, dateFormat),
                    moment(detailData.endDate, dateFormat)
                  ] : [],
                  rules: [{ required: true, message: '请选择任务时间' }]
                })(
                  <RangePicker
                    placeholder={['开始日期', '结束日期']}
                    style={{ width: '100%' }}
                    format={dateFormat}
                    disabled={this.props.readOnly}
                  />
                )}
              </Form.Item>
            </Col>
          </Row>

        </Form>

        {/* 添加共保企业 */}
        {
          this.state.shareTaskVisble &&
          <AddShareTask
            visible={this.state.shareTaskVisble}
            setParentState={this.setState.bind(this)}
            changeSelectValue={(selectedRows) => {
              const data = JSON.parse(JSON.stringify(this.state.shareTaskList))
              selectedRows.map((item) => {
                if (JSON.stringify(this.state.shareTaskList).indexOf(item.comCerNo) == -1) {
                  data.push(item)
                }
              })
              this.setState({
                shareTaskList: data,
                shareTaskVisble: false
              });
              setFieldsValue({ shareTaskList: data })
            }}
          />
        }

        {/* 关联合同 */}
        {
          this.state.contractModalVisble && <SelectContractModal
            visible={this.state.contractModalVisble}
            // setParentState={this.setState.bind(this)}
            changeSelectValue={(selectedRows) => {
              this.setState({
                comContractList: selectedRows,
              });
              setFieldsValue({ comContractList: selectedRows })
            }}
            changeVisble={(value) => {
              this.setState({
                contractModalVisble: value
              })
            }}
          />
        }
      </div>
    );
  }
}
const RodioSelector = st.div`
  position: absolute;
  top: -10px;
  left: 119px;
`;
const Btns = st.div`
  margin-bottom: 10px;
  >button{
    margin-left: 10px;
    &:first-child{
      margin-left: 0;
    }
  }
`;

const TableContainer = st.div`
  .ant-table-pagination{
    display: none;
  }
`;

