import React, { Component } from "react";
import { connect } from "dva";
import moment from "moment";
import st from "styled-components";
import {
  Form,
  Input,
  Select,
  Button,
  Radio,
  Steps,
  Checkbox,
  DatePicker,
  InputNumber,
  Modal,
  Tag,
  Table,
  message,
  Cascader,
  Row,
  Col,
  notification
} from "antd";
import {
  publicCommonDictGetDictByCodeTypes, //数字字典
  taskGetServerTypeList,//服务类型
  taskGetIndustriesList,//驻勤类型
  taskAddTask,//创建驻勤
  taskGetTaskById,//
  taskSaveStepOneDetail,
  taskGetStepOneDetail,
  // taskTreeTaskType,
  getComRegulatorSet
} from "../../../services/api";
import "../Task.less";
import PCascader from "../../../components/Pro/PCascader";
// import PTable from '../../../components/Pro/PTable';
import bcx_utils from '../../../common/bcx_utils';
import { gup } from '../../../utils/utils';
import RegulatorCascader from '../../../components/RegulatorCascader';
import SelectContractModal from './SelectContractModal';
// import { JSDOM } from "../../../../node_modules/_jsdom@11.6.2@jsdom";

const FormItem = Form.Item;
const { Option } = Select;
const { Step } = Steps;
const { TextArea } = Input;
const { RangePicker } = DatePicker;
const { CheckableTag } = Tag;
const RadioGroup = Radio.Group;
const Search = Input.Search;
const dateFormat = "YYYY-MM-DD";
const tagsFromServer = [
  "关联活动",
  "关联合同",
  "关联审批单",
  "关联合同（未开通）"
];
const dataSource = [
  {
    key: "1",
    name: "胡彦斌",
    age: 32,
    address: "西湖区湖底公园1号"
  },
  {
    key: "2",
    name: "胡彦祖",
    age: 42,
    address: "西湖区湖底公园1号"
  }
];

const columns = [
  {
    title: "项目名称",
    dataIndex: "name",
    key: "1"
  },
  {
    title: "项目类型",
    dataIndex: "age",
    key: "2"
  },
  {
    title: "项目内容",
    dataIndex: "address",
    key: "3"
  },
  {
    title: "项目开始时间",
    dataIndex: "address",
    key: "4"
  },
  {
    title: "项目结束时间",
    dataIndex: "address",
    key: "5"
  }
];

const rowSelection = {
  onChange: (selectedRowKeys, selectedRows) => {
    console.log(
      `selectedRowKeys: ${selectedRowKeys}`,
      "selectedRows: ",
      selectedRows
    );
  },
  getCheckboxProps: record => ({
    disabled: record.name === "Disabled User" // Column configuration not to be checked
  })
};

@connect(state => ({
  profile: state.profile
}))

@Form.create()
export default class CreateTaskInformation extends Component {
  state = {
    visible: false,
    visible1: false,
    modaltitle: "",
    selectedTags: [],
    taskTypes: [],//驻勤类型
    taskNatures: [], //驻勤性质
    urgentLevels: [], //紧急程度
    // serviceTypeLists: [], //服务类型
    taskLevels: [], //驻勤等级
    taskStationTypes: [],  //驻勤点类型
    serviceObjectTypes: [], //服务企业类型
    serviceObjectSySituations: [],//服务企业涉外情况
    taskStationType: '',  //驻勤点类型默认值
    taskStatus: '', //驻勤状态
    comTaskId: this.props.dataSource.comTaskId || this.props.comTaskId || "",
    param: {
      taskName: "",
      taskType: "",
      taskBigType: "",
      taskLevel: "",
      attendType: "",
      serviceType: [],
      taskNature: "",
      urgentLevel: "",
      taskContent: "",
      taskAddress: "",
      addressLongitude: "",
      addressLatitude: "",
      execRange: '',
      taskStatus: null,
      startDate: moment().format('YYYY-MM-DD') + " 00:00:00",
      endDate: moment().format('YYYY-MM-DD') + " 00:00:00",
      // perNum: "0",
      allAddress: [],//省市区
      province: "",
      city: "",
      area: "",
      serviceObject: '',
      serviceObjectType: '',
      serviceObjectSySituation: '',
    },
    startDate: moment().format('YYYY-MM-DD'),
    endDate: moment().format('YYYY-MM-DD'),
    map: "",//地图
    province: "",//省
    place: "",//地点
    searchResult: "",//地图搜索结果
    showInitialMarker: false,
    pagenav: {
      current: 1,
      pageSize: 10,
      showQuickJumper: true,
      showSizeChanger: true,
      showTotal: total => `总共 ${total} 条`,
      onShowSizeChange: (current, pageSize) => {
        const pagenav = Object.assign({}, this.state.pagenav);
        pagenav.current = current;
        pagenav.pageSize = pageSize;
        this.setState({ pagenav });
        setTimeout(() => {
          this.bbdExampersonPage();
        });
      },
      onChange: (page, pageSize) => {
        const pagenav = Object.assign({}, this.state.pagenav);
        pagenav.current = page;
        pagenav.pageSize = pageSize;
        this.setState({ pagenav });
        setTimeout(() => {
          this.bbdExampersonPage();
        });
      },
      total: 0
    },
    // cascaderOptions: [],//驻勤级联数据
    // regulateInfo: {},  //监管信息

    contractModalVisble: false,
    comContractList: [],  //合同列表
    clickMark:false
  };

  componentWillMount() {
    this.taskGetTaskById();
  }

  componentDidMount() {
    // this.__getComRegulatorSet();
    this.loadMapScript();
    // this.getTaskGetServerTypeList();
    this.getTaskGetIndustriesList();
    // this.taskTreeTaskType();
    //数字字典
    publicCommonDictGetDictByCodeTypes({
      codeTypes: "taskType,serviceTypeList,taskNature,urgentLevel,taskLevel,taskStationType,serviceObjectType,serviceObjectSySituation"
    }).then(
      data => {
        console.log(data, "publicCommonDictGetDictByCodeTypes-data");
        const dict = data.data;
        this.setState({
          taskNatures: dict.taskNature || [], //驻勤性质
          urgentLevels: dict.urgentLevel || [], //紧急程度
          taskLevels: dict.taskLevel || [], //驻勤等级
          taskStationTypes: dict.taskStationType || [], //驻勤点类型
          serviceObjectTypes: dict.serviceObjectType || [],
          serviceObjectSySituations: dict.serviceObjectSySituation || []
        });
      },
      err => {
        console.log(err, "publicCommonDictGetDictByCodeTypes-err");
      }
    );
  }
  //获取已经配置过机构的信息
  __getComRegulatorSet() {
    getComRegulatorSet().then(
      res => {
        if (res.retType === '0') {
          this.setState({
            regulateInfo: res.data
          });
        }
      }
    )
  }
  /* 基础信息 */
  taskGetTaskById = () => {

    let comTaskId = this.state.comTaskId;
    if (comTaskId == '') {
      return;
    }
    // 获取页面详情
    taskGetStepOneDetail({ comTaskId }).then(
      data => {
        data.data.serviceType = data.data.serviceType.split(',');
        const param = { ...this.state.param };
        for (const key in data.data) {
          if (data.data.hasOwnProperty(key) === true) {
            param[key] = data.data[key];
          }
        }
        this.setState({
          comContractList: param.comContractList
        });
        this.setState({ param, taskStatus: data.data.taskStatus });
        this.setState({ place: param.taskAddress });
        this.setState({ startDate: param.startDate });
        this.setState({ endDate: param.endDate });
        this.setState({ provinceValue: [param.province , param.city , param.area ]});
        this.setState({ showInitialMarker: true });
        const taskStationType = data.data.taskStationType || '';
        this.setState({
          taskStationType
        });
      },
      err => {
        console.log(err, "taskGetStepOneDetail-err");
      }
    );
  };
  //时间选择
  // onChangeTime = (date, dateString) => {
  //   this.setState({
  //     startDate: dateString[0],
  //     endDate: dateString[1]
  //   });
  // };
  handleSubmit = e => {
    e.preventDefault();

    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        if (this.state.comTaskId != '') {
          values.comTaskId = this.state.comTaskId;
        }
        const { comContractList } = this.state;
        if(comContractList.length == 0) {
          return message.warning('请选择合同');
        }
        if(comContractList.length > 1) {
          return message.warning('只允许关联一个合同');
        }
        values.comContractId = comContractList[0].comContractId;
        
        values.addressLatitude = this.state.param.addressLatitude;
        values.addressLongitude = this.state.param.addressLongitude;
        if (values.addressLatitude === '' && values.addressLongitude === '') {
          message.warning(`请输入地图定位地址并搜索，选择合适的标注点进行选址。`);
          return;
        }
        // const [taskBigType, taskType] = values.taskType;
        // values.taskType = taskType;
        // values.taskBigType = taskBigType;
        // 应产品要求，临时处理
        values.taskNature = '1';
        values.urgentLevel = '1';
        values.serviceType = '1010009';
        values.taskLevel = '1';

        // 时间处理
        if (values.startDate.valueOf() >= values.endDate.valueOf()) {
          return message.error("结束时间不能小于开始时间");
        }
        values.startDate = values.startDate.format(dateFormat);
        values.endDate = values.endDate.format(dateFormat);
        // const currentTime = moment().format('YYYY-MM-DD') + " 00:00:00";

        // if (moment(values.endDate).diff(moment(), 'seconds') < 0 && (currentTime !== values.endDate)) {
        //   bcx_utils.preventRA((resolve) => {
        //     message.error("结束时间不能小于当前时间", 1.5, () => {
        //       setTimeout(() => {
        //         resolve();
        //       }, 2000);
        //     });
        //   });
        //   return;
        // }
        if(!values.regulator[0]) {
          return message.warning(`请选择监管机构`);
        }
        if(this.state.clickMark){
          return message.warning("请选择一个定位地址");
        }
        values.cityOrgId = values.regulator[0];
        values.districtOrgId = values.regulator[1];
        values.policeStationId = values.regulator[2];
        Reflect.deleteProperty(values, 'regulator');
        
        this.taskManagementAddTaskStepOne(values);
      }
    });
  };
  //获取服务类型
  // getTaskGetServerTypeList = () => {
  //   taskGetServerTypeList().then(
  //     data => {
  //       this.setState({ serviceTypeLists: data.data });
  //       console.log(data, "获取服务类型");
  //     },
  //     err => {
  //       console.log(err, "获取服务类型-err");
  //     }
  //   );
  // }
  //获取驻勤类型
  getTaskGetIndustriesList = () => {
    taskGetIndustriesList().then(
      data => {
        this.setState({ taskTypes: data.data });
        console.log(data, "获取驻勤类型");
      },
      err => {
        console.log(err, "获取驻勤类型-err");
      }
    );
  }
  //创建驻勤第一个步骤
  taskManagementAddTaskStepOne = (postdata) => {
    taskSaveStepOneDetail(postdata).then(
      data => {
        this.props.updateTable && this.props.updateTable();
        const comTaskId = this.state.comTaskId === '' ? data.data : this.state.comTaskId;
        if (this.props.onClose) {
          notification.success({
            // message: data.msg
            message: '保存成功'
          });
          this.props.onClose();
        } else {
          this.props.switchStep && this.props.switchStep(1, comTaskId, this.state.taskStatus);
        }
      },
      err => {
        console.log(err, "taskSaveStepOneDetail-err");
      }
    );
  };

  //获取所有大小驻勤类型树形
  // taskTreeTaskType = () => {
  //   taskTreeTaskType().then(({ data = [] }) => {
  //     let newData = JSON.stringify(data);
  //     newData = newData.replace(/bigKey/g, "key");
  //     newData = newData.replace(/bigValue/g, "value");
  //     newData = newData.replace(/value/g, "label");
  //     newData = newData.replace(/key/g, "value");
  //     newData = JSON.parse(newData);
  //     this.setState({ cascaderOptions: newData });
  //   }, (err) => {
  //     console.log(err);
  //   });
  // }


  showModal = () => {
    this.setState({
      visible: true
    });
  };
  handleOk = e => {
    this.setState({
      visible: false
    });
  };
  handleCancel = e => {
    this.setState({
      visible: false
    });
  };
  addressChange = (address) => {
    this.setState({ province: address });
  }
  //地图模块方法
  changeProvinceValue = (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 ,clickMark:true});
    setFieldsValue({ taskAddress: place });

  }
  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) => {
    console.log(e.target.value)
    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;
    }
  }
  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.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('mapContainer', 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;
    console.log(this.state.province)
    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) {
        console.log(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;
        console.log('搜索结果', searchResult);
        console.log('this.state.place', that.state.place);
        //查看是否有完全符合的结果
        searchResult.map((item, index) => {
          if (place === item.name) {
            searchResult = [];
            searchResult.push(item)
            console.log('找到完全符合的结果', 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 });
        console.log(lng, lat);
        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);
        });
      });
    })
  }


  addMarker = (lng, lat, index) => {
    let searchResult = this.state.searchResult;
    let map = this.state.map;
    let markers = this.state.markers;
    let place = this.state.place;
    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 ,clickMark:false});
        const { setFieldsValue } = that.props.form;
        setFieldsValue({ taskAddress: province + searchResult[index].name });
      });
    // }
  }

  //返回上一个页面
  returnLastPage = () => {
    // const model = gup("model") || "";

    //model==="detail"表示从驻勤详情跳转过来
    // if (model === "detail") {
    //   const id = gup("id").toString();
    //   this.props.history.push(`/taskmanager/tasklist/taskDetail?id=${id}`);
    //   return;
    // }
    this.props.history.push('/taskmanager/tasklist')
  }

  render() {
    const { submitting } = this.props;
    const { getFieldDecorator } = this.props.form;
    const {
      selectedTags,
      taskTypes,//驻勤类型
      taskNatures, //驻勤性质
      urgentLevels, //紧急程度
      // serviceTypeLists, //服务类型
      taskLevels //驻勤等级
    } = this.state;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 }
      }
    };

    const submitFormLayout = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 10, offset: 7 }
      }
    };
    const { startDate, endDate, taskType, taskBigType } = this.state.param;
    const ifEdit = this.state.param.taskStatus === "1";//判断是否可以编辑
    // const { cascaderOptions } = this.state;

    return (
      <div className="CreateTask">
        {
          // 改成弹窗以后只显示基础信息 通过onClose字段判断是否展示步骤
          !this.props.onClose &&
          <div className="Steps">
            <Steps current={0}>
              <Step title="基本信息" />
              <Step title="出勤设置" />
              <Step title="发布设置" />
            </Steps>
          </div>
        }
        <Row>
          <Col span={7} style={{textAlign: 'right'}}>
            <Button type="primary"
              onClick={() => {
                this.setState({
                  contractModalVisble: true,
                });
              }}
            >关联合同</Button>
          </Col>
          <Col span={17}>
            <span style={{color: 'orange', lineHeight: '30px', marginLeft: 10}}>请关联该任务相应的合同；只能关联一份，若需要修改，请先移除关联。</span>
          </Col>
        </Row>

        <TableContainer>
          <Table
            style={{ width: '80%', margin: '20px auto' }}
            columns={[
              {
                title: '合同名称',
                dataIndex: 'contractName',
                key: 'contractName',
                width: 120,
                fixed: 'left',
                render: (text, record) => (
                    <div
                      style={{
                        maxWidth: '300px',
                        whiteSpace: 'nowrap',
                        textOverflow: 'ellipsis',
                        overflow: 'hidden',
                        marginTop: '8px',
                        marginBottom: '8px'
                      }}
                    >
                      {record.contractName}
                    </div>
                )
              },
              {
                title: '合同类型',
                dataIndex: 'contractType_name',
                key: 'contractType_name',
                // width: 100,
                render: (text, record) => (
                  <span
                    style={{
                      // width: '100px',
                      whiteSpace: 'nowrap',
                      textOverflow: 'ellipsis',
                      overflow: 'hidden'
                    }}
                  >
                    {record.contractType_name}
                  </span>
                )
              },
              {
                title: '企业档案编号',
                dataIndex: 'comFileNo',
                key: 'comFileNo'
              },
              {
                title: '甲方名称',
                dataIndex: 'firstPartyName',
                key: 'firstPartyName'
              },
              {
                title: '乙方名称',
                dataIndex: 'secondPartyName',
                key: 'secondPartyName'
              },
              {
                title: '丙方名称',
                dataIndex: 'thirdPartyName',
                key: 'thirdPartyName'
              },
              {
                title: '合同开始时间',
                dataIndex: 'effectStartDate',
                key: 'effectStartDate'
              },  
              {
                title: '合同结束时间',
                dataIndex: 'effectEndDate',
                key: 'effectEndDate'
              },   
              {
                title: '合同状态',
                dataIndex: 'contractEffect',
                key: 'contractEffect',
                // width: 100,
                render: (text, record) => {
                  let status = '';
                  switch (true) {
                    case text == '未生效':
                      status = 'warning';
                      break;
                    case text == '有效':
                      status = 'success';
                      break;
                    case text == '终止':
                      status = 'error';
                  }
          
                  return (
                    <div>
                      <span>{text}</span>
                    </div>
                  );
                }
              },
              {
                title: '最后修改时间',
                dataIndex: 'lastUpdateTime',
                key: 'lastUpdateTime',
                // width: 150,
                render: (text, record) => (
                  <span
                    style={{
                      width: '150px',
                      whiteSpace: 'nowrap',
                      textOverflow: 'ellipsis',
                      overflow: 'hidden'
                    }}
                  >
                    {record.lastUpdateTime}
                  </span>
                )
              },
              // {
              //   title: '操作',
              //   key: 'action',
              //   width: 120,
              //   fixed: 'right',
              //   render: (text, record) => {
              //     // contractStatus 合同类型（1：已签订:2：已完成、9：已终止，3：已续签）
              //     return(
              //       <div>
              //         <a href="javascript:void(0)" style={{color: 'red'}} onClick={() => {
              //           this.setState({
              //             comContractList: []
              //           });
              //         }}>移除关联</a>
              //       </div>
              //     );
              //   }
              // }
            ]}
            dataSource={this.state.comContractList}
            scroll={{x: '1500px'}}
          />
        </TableContainer>
        <Form onSubmit={this.handleSubmit} style={{ marginTop: 24 }}>
          <FormItem {...formItemLayout} label="驻勤名称" extra={<span style={{color: 'orange'}}>注:请按照保安服务合同约定的驻勤名称填写，不要简写，确保驻勤点可查可确认。</span>}>
            {getFieldDecorator("taskName", {
              initialValue: this.state.param.taskName,
              rules: [
                {
                  pattern: /^.{1,50}$/,
                  required: true,
                  message: "请输入少于50个字"
                }
              ]
            })(<Input placeholder="请输入" />)}
          </FormItem>
          {/* <FormItem {...formItemLayout} label="所属类型">
            {getFieldDecorator("taskType", {
              initialValue: [taskBigType, taskType],
              rules: [{ required: true, message: "请选择" }]
            })(
              <Cascader options={cascaderOptions} placeholder="请输入" />
            )}
          </FormItem> */}
          <FormItem {...formItemLayout} label="驻勤点类型">
            {getFieldDecorator("taskStationType", {
              initialValue: this.state.taskStationType,
              rules: [{ required: true, message: "请选择" }]
            })(

              <Select placeholder="请选择">
                {this.state.taskStationTypes.map((item, index) => {
                  return (
                    <Option key={index} value={item.codeValue}>{item.label}</Option>
                  );
                })}
              </Select>
            )}
          </FormItem>

          <FormItem {...formItemLayout} label="监管机构">
            {getFieldDecorator("regulator", {
              initialValue: [
                this.state.param.cityOrgId,
                this.state.param.districtOrgId,
                this.state.param.policeStationId
              ],
              rules: [{ required: true, message: "请选择" }]
            })(
              <RegulatorCascader />
            )}
          </FormItem>
          {/* <FormItem {...formItemLayout} label="驻勤性质">
            {getFieldDecorator("taskNature", {
              initialValue: this.state.param.taskNature,
              rules: [{ required: true, message: "请选择驻勤性质" }]
            })(
              <RadioGroup disabled={ifEdit}>
                {taskNatures && taskNatures.map(val => {
                  return (
                    <Radio key={val.configDictId} value={val.codeValue}>
                      {val.label}
                    </Radio>
                  );
                })}
              </RadioGroup>
            )}
          </FormItem> */}

          <FormItem {...formItemLayout} label="服务企业名称">
            {getFieldDecorator("serviceObject", {
              initialValue: this.state.param.serviceObject,
              rules: [
                {
                  pattern: /^.{1,50}$/,
                  required: true,
                  message: "请输入少于50个字"
                }
              ]
            })(<Input placeholder="请输入关联合同中的服务企业全称" />)}
          </FormItem>
          {/* <FormItem {...formItemLayout} label="服务企业类型">
            {getFieldDecorator("serviceObjectType", {
              initialValue: this.state.param.serviceObjectType,
              rules: [{ required: true, message: "请选择" }]
            })(
              <Select placeholder="请选择">
                {this.state.serviceObjectTypes.map((item, index) => {
                  return (
                    <Option key={index} value={item.codeValue}>{item.label}</Option>
                  );
                })}
              </Select>
            )}
          </FormItem> */}
          <FormItem {...formItemLayout} label="服务企业涉外情况">
            {getFieldDecorator("serviceObjectSySituation", {
              initialValue: this.state.param.serviceObjectSySituation,
              rules: [{ required: true, message: "请选择" }]
            })(

              <Select placeholder="请选择">
                {this.state.serviceObjectSySituations.map((item, index) => {
                  return (
                    <Option key={index} value={item.codeValue}>{item.label}</Option>
                  );
                })}
              </Select>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label="是否治安保卫重点单位">
            {getFieldDecorator("isSecurityImportantUnit", {
              initialValue: this.state.param.isSecurityImportantUnit ? this.state.param.isSecurityImportantUnit : '',
              rules: [{ required: true, message: "请选择" }]
            })(

              <Select placeholder="请选择">
                <Option value="0">否</Option>
                <Option value="1">是</Option>
              </Select>
            )}
          </FormItem>
          {/* <FormItem {...formItemLayout} label="紧急程度">
            {getFieldDecorator("urgentLevel", {
              initialValue: this.state.param.urgentLevel,
              rules: [
                {
                  required: true,
                  message: "请选择紧急程度"
                }
              ]
            })(
              <RadioGroup disabled={ifEdit}>
                {urgentLevels && urgentLevels.map(val => {
                  return (
                    <Radio key={val.configDictId} value={val.codeValue}>
                      {val.label}
                    </Radio>
                  );
                })}
              </RadioGroup>
            )}
          </FormItem> */}
          {/* <FormItem {...formItemLayout} label="服务类型">
            {getFieldDecorator("serviceType", {
              initialValue: this.state.param.serviceType,
              rules: [
                {
                  required: true,
                  message: "请选择服务类型"
                }
              ]
            })(
              <Checkbox.Group disabled={ifEdit}>
                {serviceTypeLists && serviceTypeLists.map(val => {
                  return (
                    <Checkbox key={val.codeValue} value={val.codeValue}>
                      {val.label}
                    </Checkbox>
                  );
                })}
              </Checkbox.Group>
            )}
          </FormItem> */}

          <FormItem {...formItemLayout} label="驻勤内容" 
          // extra={<span style={{color: 'orange'}}>
          //   注：驻勤地区、详细地址、驻勤时间发布后将不能修改，请注意根据关联的合同填写。
          // </span>}
          >
            {getFieldDecorator("taskContent", {
              initialValue: this.state.param.taskContent,
              rules: [
                {
                  required: true,
                  message: "请输入驻勤内容"
                },
                {
                  max: 1000,
                  message: "请输入少于1000个字符"
                },
              ]
            })(<TextArea  placeholder="请输入关联合同中，约定改驻勤点需要进行的驻勤内容。" autosize={{ minRows: 3, maxRows: 6 }} />)}
          </FormItem>
          <FormItem {...formItemLayout} label="驻勤城市">
            {getFieldDecorator("allAddress", {
              initialValue: this.state.param.allAddress,
              rules: [
                {
                  required: true,
                  message: "请选择驻勤城市"
                },
              ]
            })(<PCascader
              // disabled={ifEdit}
              placeholder="请选择省市区"
              onChange={this.changeProvinceValue}
              addressChange={this.addressChange}
              provinceValue={this.state.provinceValue}
              changeNumToAddress={(value)=>{
                this.setState({
                  province:value
                })
              }}
            />)}
          </FormItem>
          <FormItem {...formItemLayout} label="驻勤精确地址">
            {getFieldDecorator("taskExactAddress", {
              initialValue: this.state.param.taskExactAddress,
              rules: [
                {
                  required: true,
                  message: "请输入驻勤精确地址"
                },
                {
                  max: 100,
                  message: "请输入少于100个字"
                },
              ]
            })(<Input placeholder="请输入驻勤精确地址" />)}
          </FormItem>
          <FormItem {...formItemLayout} label="地图定位地址">
            {getFieldDecorator("taskAddress", {
              initialValue: this.state.param.taskAddress,
              rules: [
                {
                  required: true,
                  message: "请输入地图定位地址"
                },
                {
                  max: 100,
                  message: "请输入少于100个字"
                },
              ]
            })(<Input
              // disabled={ifEdit}
              placeholder="请输入详细地址后enter或点击搜索按钮。"
              onPressEnter={this.handleKeyUp}
              onChange={this.handleInputSearch}
            />)}
            <Button
              // disabled={ifEdit}
              type="primary"
              style={{ position: 'absolute', top: -7, right: 0 }}
              shape="circle"
              icon="search"
              onClick={this.handleKeyUp} />
          </FormItem>
          <FormItem {...submitFormLayout} label="" extra={this.state.clickMark?<span style={{color:'red'}}>请选择一个定位地址</span>:''}>
            <div style={{ width: '100%', height: 230, overflow: 'hidden' }}>
              <div id="mapContainer" style={{ width: '100%', height: 250 }}></div>
            </div>
          </FormItem>
          <FormItem {...formItemLayout} label="执行范围" extra={<span style={{color: 'orange'}}>注：驻勤时间请根据关联的合同有效期填写，确保驻勤点与合同时间一致。</span>}>
            {getFieldDecorator("execRange", {
              initialValue: this.state.param.execRange,
              rules: [
                {
                  required: true,
                  pattern: /^\d{0,10}$/,
                  message: "请输入少于10个数字"
                },
                {}
              ]
            })(<Input addonAfter="米" />)}
          </FormItem>

          {/*二期
           <FormItem
            {...formItemLayout}
            label="关联项" >
            {getFieldDecorator('fax', {
              rules: [{
                required: false,
              }, {
                validator: this.checkPhone
              }],
            })(
              <div>
                <Button type="primary" onClick={this.showModal} ghost>添加关联项目</Button>
                <div className="glxm">
                  <dl>
                    <dt>关联项目：<Button onClick={() => { this.setState({ visible1: true, modaltitle: "选择项目" }); }} size="small" icon="plus">添加项目</Button></dt>
                    <dd>
                      <Icon type="paper-clip" /> <div>项目名称</div> <Icon type="close" />
                    </dd>
                    <dd>
                      <Icon type="paper-clip" /> <div>项目名称</div> <Icon type="close" />
                    </dd>
                    <dd>
                      <Icon type="paper-clip" /> <div>项目名称</div> <Icon type="close" />
                    </dd>
                  </dl>
                  <dl>
                    <dt>关联合同：<Button onClick={() => { this.setState({ visible1: true, modaltitle: "选择合同" }); }} size="small" icon="plus">添加项目</Button></dt>
                    <dd>
                      <Icon type="paper-clip" /> <div>项目名称</div> <Icon type="close" />
                    </dd>
                    <dd>
                      <Icon type="paper-clip" /> <div>项目名称</div> <Icon type="close" />
                    </dd>
                    <dd>
                      <Icon type="paper-clip" /> <div>项目名称</div> <Icon type="close" />
                    </dd>
                    <dd>
                      <Icon type="paper-clip" /> <div>项目名称</div> <Icon type="close" />
                    </dd>
                  </dl>
                </div>
              </div>
              )}
          </FormItem> */}

          {/* <FormItem {...formItemLayout} label="起止时间">
            {getFieldDecorator("taskDate", {
              initialValue: [
                moment(startDate, dateFormat),
                moment(endDate, dateFormat),
              ],
              rules: [{ required: true, message: "请选择生效日期" }]
            })(
              <RangePicker
                // disabled={ifEdit}
                placeholder={["开始日期", "结束日期"]}
                style={{ width: "100%" }}
                format={dateFormat}
                onChange={this.onChangeTime}
                // disabledDate={current => {
                //   return current && current < moment(parseInt(sessionStorage.getItem('requestDate'))).startOf('day');
                // }}
              />
            )}
          </FormItem> */}
          <FormItem {...formItemLayout} label="开始日期" extra={this.state.comTaskId ? <span style={{ color: 'orange' }}>注：新的开始日期不能晚于上一次设置的日期时间。</span> : ''}>
            {getFieldDecorator("startDate", {
              initialValue: moment(startDate, dateFormat),
              rules: [{ required: true, message: "请选择开始日期" }]
            })(
              <DatePicker
                // disabled={ifEdit}
                placeholder="开始日期"
                style={{ width: "100%" }}
                format={dateFormat}
                disabledDate={current => {
                  if (this.state.comTaskId) {
                    return current && current > moment(startDate).startOf('day');
                  }
                  return false;
                }}
              />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label="结束日期" extra={!this.state.comTaskId ? '' : <span style={{ color: 'orange' }}>注：若您需要调整驻勤点的结束日期，请使用列表操作的“延期”功能。</span>}>
            {getFieldDecorator("endDate", {
              initialValue: moment(endDate, dateFormat),
              rules: [{ required: true, message: "请选择结束日期" }]
            })(
              <DatePicker
                disabled={!!this.state.comTaskId}
                placeholder="结束日期"
                style={{ width: "100%" }}
                format={dateFormat}
                disabledDate={current => {
                  // return (current && current < moment(endDate, dateFormat));
                }}
              />
            )}
          </FormItem>
          {/*<FormItem {...formItemLayout} label="所需人数">*/}
          {/*{getFieldDecorator("perNum", {*/}
          {/*initialValue: this.state.param.perNum,*/}
          {/*rules: [{*/}
          {/*pattern: /^[1-9][0-9]*$/,*/}
          {/*required: true, message: "请选择所需人数"*/}
          {/*}]*/}
          {/*})(<InputNumber min={1} max={1000000000} disabled={ifEdit}/>)}*/}
          {/*</FormItem>*/}
          {/* <FormItem {...formItemLayout} label="驻勤等级">
            {getFieldDecorator("taskLevel", {
              initialValue: this.state.param.taskLevel,
              rules: [
                {
                  required: true,
                  message: "请选择"
                }
              ]
            })(
              <RadioGroup disabled={ifEdit}>
                {taskLevels && taskLevels.map(val => {
                  return (
                    <Radio key={val.configDictId} value={val.codeValue}>
                      {val.label}
                    </Radio>
                  );
                })}
              </RadioGroup>
            )}
          </FormItem> */}
          {
            !this.props.onClose &&
            <FormItem {...submitFormLayout} style={{ marginTop: 32 }}>
              <Button loading={submitting} onClick={this.returnLastPage}>取消</Button>
              <Button type="primary" style={{ marginLeft: 8 }} htmlType="submit">下一步</Button>
            </FormItem>
          }
          {
            this.props.onClose &&
            <FormItem {...submitFormLayout} style={{ marginTop: 32 }}>
              <Button type="primary" htmlType="submit" disabled={this.state.taskStatus == 4 || this.state.taskStatus == 7 || this.state.taskStatus == 2}>保存</Button>
              <Button loading={submitting} style={{ marginLeft: 8 }} onClick={this.props.onClose}>取消</Button>
            </FormItem>
          }
        </Form>

        <Modal
          title="选择关联项"
          cancelText="取消"
          okText="确定"
          visible={this.state.visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
        >
          {tagsFromServer && tagsFromServer.map(tag => (
            <CheckableTag
              key={tag}
              checked={selectedTags.indexOf(tag) > -1}
              onChange={checked => this.handleChange(tag, checked)}
            >
              {tag}
            </CheckableTag>
          ))}
        </Modal>

        <Modal
          title={this.state.modaltitle}
          cancelText="取消"
          okText="确定"
          width={900}
          visible={this.state.visible1}
          closable={false}
          onOk={() => {
            this.setState({ visible1: false });
          }}
          onCancel={() => {
            this.setState({ visible1: false });
          }}
        >
          <div className="CreateTask-select-project">
            <Table
              rowSelection={rowSelection}
              pagination={this.state.pagenav}
              dataSource={dataSource}
              columns={columns}
            />
          </div>
        </Modal>

        <SelectContractModal 
          visible={this.state.contractModalVisble}
          setParentState={this.setState.bind(this)}
        />
      </div>
    );
  }
}


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