// 药品配送地址
import React from 'react';
import {Modal, Input, Select, DatePicker, Form, message} from 'antd';
import { $http } from 'containers/config/https';
import Moment from 'moment';

const {Option} = Select;
const { TextArea } = Input;
const FormItem = Form.Item;

class DrugDeliveryAddress extends React.Component {
  constructor() {
    super();
    var userData = JSON.parse(sessionStorage.getItem('userData'));
    this.state = {
      userData,
      visible: false,
      methods: 0,
      rowData: {},
      provinceSelectData: [], // 省下拉数据
      cityIdSelectData: [], // 市下拉数据
      areaSelectData: [], // 区下拉数据
      villageSelectData: [], // 街道下拉框数据
      userInfo: {}, // 选中行form数据
    }
  }

  componentDidMount() {
    this.props.onRef(this);
  }
  
  // 获取主列表columns
  getTableColumns = () => {
    let {userData} = this.state;
    let data = {
      params: [{
        compontName: "DrugDeliveryAddress",
        reactCode: ['DrugDeliveryAddress']
      }]
    }
    $http.post('urlS', this, {
      code: '01040073',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          this.setState({
            localeProvider: userData.language == 'EN' ? res.result.language.EN : res.result.language.CN
          })
        }
      }
    })
  }

	//国际化
	setMessage = (name, message, defaultTitle) => {
		return this.state.localeProvider&&this.state.localeProvider[name] ? this.state.localeProvider[name][message] : defaultTitle
  }

  // 获取市下拉数据
  getCityIdSelectData = (provinceId) => {
    let data = {
      params: [{
        provinceId, // 市ID
      }]
    }
    $http.post('urlS', this, {
      code: '02070004',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          this.setState({cityIdSelectData: res.result})
        }
      }
    })
  }
  
  // 获取区下拉数据
  getAreaSelectData = (cityId) => {
    let data = {
      params: [{
        cityId, // 市ID
      }]
    }
    $http.post('urlS', this, {
      code: '02070005',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          this.setState({areaSelectData: res.result})
        }
      }
    })
  }

  // 获取街道下拉数据
  getVillageSelectData = (areaId) => {
    let data = {
      params: [{
        areaId, // 区ID
      }]
    }
    $http.post('urlS', this, {
      code: '02070006',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          this.setState({villageSelectData: res.result})
        }
      }
    })
  }

  // 获取默认地址
  getDefaultAddress = () => {
    let {rowData, methods} = this.state;
    let data = {
      params: [{
        KMID: rowData&&rowData.KMID, // 康美处方ID
        methods, // 配送方式
        patID: rowData&&rowData.patID, // 病人ID
      }]
    }
    $http.post('urlS', this, {
      code: '02070008',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          this.setState({userInfo: res.result}, () => {
            // 获取区以及街道地址
            this.getAreaSelectData(this.state.userInfo.cityID);
            this.getVillageSelectData(this.state.userInfo.areaID);
          })
        }
      }
    })
  }

  // 打开弹窗
  handleShowModal = (rowData, selectData, methods) => {
    let {userData} = this.state;
    let provinceSelectData = selectData&&selectData.province ? selectData.province : [];
    let cityIdSelectData = selectData&&selectData.city ? selectData.city : [];
    this.setState({visible: true, rowData, cityIdSelectData, provinceSelectData, methods}, () => {
      this.getDefaultAddress();
      !this.state.localeProvider&&userData.language == 'EN' ? this.getTableColumns() : "";
    });
  }

  // 关闭弹窗
  handleCancel = () => {
    this.setState({visible: false});
  }

  // 输入下拉框option
  exportSelectOption = (data) => {
		let selectOption = data && data.map((item, index) => {
			return (<Option key={index} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
    })
    return selectOption;
  }

  // 选择省查询市数据
  handleProvinceSelect = e => {
    this.getCityIdSelectData(e);
    this.props.form.setFieldsValue({
      cityID: undefined, // 市
      areaID: undefined, // 区
      villageID: undefined, // 街道
    })
  }

  // 选择市查询区数据
  handleCitySelect = e => {
    this.getAreaSelectData(e);
    for(var i = 0; i < this.state.cityIdSelectData.length; i++) {
      if (this.state.cityIdSelectData[i].id === e) {
        // 默认选上该市属于的省
        this.props.form.setFieldsValue({
          provinceID: this.state.cityIdSelectData[i].province, // 省
          areaID: undefined, // 区
          villageID: undefined, // 街道
        })
        return;
      }
    }
  }

  // 选择区查询街道数据
  handleAreaSelect = e => {
    this.getVillageSelectData(e);
    this.props.form.setFieldsValue({
      villageID: undefined, // 街道
    })
  }

  // 确认
  handleOk = () => {
    const { form: { validateFields } } = this.props;
    validateFields((errors, values) => {
      // 验证成功
      if (errors === null) {
        let data = {
          params: []
        }

        let obj = JSON.parse(JSON.stringify(values));
        obj.KMID = this.state.rowData&&this.state.rowData.KMID ? this.state.rowData.KMID : "";
        obj.prescno = this.state.rowData&&this.state.rowData.prescno ? this.state.rowData.prescno : "";
        obj.methods = this.state.methods;
        obj.sendDate = obj.sendDate ? Moment(obj.sendDate).format('YYYY-MM-DD') : "";

        // 处理需要传递的obj
        data.params.push(obj);
        $http.post('urlADS', this, {
          code: "02070009",
          data: data,
          success: function (res) { 
            if (+res.errorCode === 0) {
              message.success(res.errorMessage);
              this.handleCancel();
              this.props.handleQuery();
            }
          }
        })
      }
    });
  }

  render() {
    let {visible, provinceSelectData, cityIdSelectData, areaSelectData, villageSelectData, userInfo, methods, userData} = this.state;
    const { getFieldDecorator } = this.props.form;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: userData&&userData.language == 'EN' ? 10 : 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: userData&&userData.language == 'EN' ? 14 : 18 },
      },
      labelAlign: "right"
    };
    return (
      <Modal
        title={<div>{this.setMessage("DrugDeliveryAddressDelivery_address", "descripts", "配送地址")}({methods === 1 ? this.setMessage("DrugDeliveryAddressHospital", "descripts", "医院") : this.setMessage("DrugDeliveryAddressHome", "descripts", "家里")})</div>}
        visible={visible}
        onOk={this.handleOk}
        onCancel={this.handleCancel}
      >
        <Form {...formItemLayout}>
          <FormItem label={this.setMessage("DrugDeliveryAddressConsignee", "descripts", "收货人：")}>
            {getFieldDecorator('consignee', {
              initialValue: userInfo.consignee ? userInfo.consignee: undefined,
              rules: [{ required: true, message: this.setMessage("DrugDeliveryAddressConsignee", "message", "收货人不能为空") }]
            })(
              <Input placeholder={this.setMessage("DrugDeliveryAddressPlease_input", "descripts", "请输入")} className='input' />
            )}
          </FormItem>
          <FormItem label={this.setMessage("DrugDeliveryAddressContactNumber", "descripts", "联系电话：")}>
            {getFieldDecorator('mobile', {
              initialValue:userInfo.mobile ? userInfo.mobile: undefined,
              rules: [{ required: true, message: this.setMessage("DrugDeliveryAddressContactNumber", "message", "联系电话不能为空") }]
            })(
              <Input placeholder={this.setMessage("DrugDeliveryAddressPlease_input", "descripts", "请输入")} className='input' />
            )}
          </FormItem>
          <FormItem label={this.setMessage("DrugDeliveryAddressDelivery_date", "descripts", "配送日期：")}>
            {getFieldDecorator('sendDate', {
              initialValue:userInfo.sendDate ? Moment(userInfo.sendDate): undefined,
            })(
              <DatePicker placeholder={this.setMessage("DrugDeliveryAddressPlease_choose", "descripts", "请选择")} allowClear={false} style={{width: "100%"}} />
            )}
          </FormItem>
          <FormItem label={this.setMessage("DrugDeliveryAddressProvince", "descripts", "省：")}>
            {getFieldDecorator('provinceID', {
              initialValue:userInfo.provinceID ? userInfo.provinceID: undefined,
              rules: [{ required: true, message: this.setMessage("DrugDeliveryAddressProvince", "message", "省不能为空") }]
            })(
              <Select showSearch optionFilterProp="seatchprop" allowClear placeholder={this.setMessage("DrugDeliveryAddressPlease_choose", "descripts", "请选择")} onSelect={this.handleProvinceSelect}>
                {this.exportSelectOption(provinceSelectData)}
              </Select>
            )}
          </FormItem>
          <FormItem label={this.setMessage("DrugDeliveryAddressCity", "descripts", "市：")}>
            {getFieldDecorator('cityID', {
              initialValue:userInfo.cityID ? userInfo.cityID: undefined,
              rules: [{ required: true, message: this.setMessage("DrugDeliveryAddressCity", "message", "市不能为空") }]
            })(
              <Select showSearch optionFilterProp="seatchprop" allowClear placeholder={this.setMessage("DrugDeliveryAddressPlease_choose", "message", "请选择")} onSelect={this.handleCitySelect}>
                {this.exportSelectOption(cityIdSelectData)}
              </Select>
            )}
          </FormItem>
          <FormItem label={this.setMessage("DrugDeliveryAddressDistrict", "descripts", "区：")}>
            {getFieldDecorator('areaID', {
              initialValue:userInfo.areaID ? userInfo.areaID: undefined,
              rules: [{ required: true, message: this.setMessage("DrugDeliveryAddressDistrict", "message", "区不能为空") }]
            })(
              <Select showSearch optionFilterProp="seatchprop" allowClear placeholder={this.setMessage("DrugDeliveryAddressPlease_choose", "message", "请选择")} onSelect={this.handleAreaSelect}>
                {this.exportSelectOption(areaSelectData)}
              </Select>
            )}
          </FormItem>
          <FormItem label={this.setMessage("DrugDeliveryAddressStreet", "descripts", "街道：")}>
            {getFieldDecorator('villageID', {
              initialValue:userInfo.villageID ? userInfo.villageID: undefined,
              rules: [{ required: true, message: this.setMessage("DrugDeliveryAddressStreet", "message", "街道不能为空") }]
            })(
              <Select showSearch optionFilterProp="seatchprop" allowClear placeholder={this.setMessage("DrugDeliveryAddressPlease_choose", "message", "请选择")} >
                {this.exportSelectOption(villageSelectData)}
              </Select>
            )}
          </FormItem>
          <FormItem label={this.setMessage("DrugDeliveryAddressDetailed_address", "descripts", "详细地址：")}>
            {getFieldDecorator('address', {
              initialValue:userInfo.address ? userInfo.address: undefined,
              rules: [{ required: true, message: this.setMessage("DrugDeliveryAddressDetailed_address", "message", "详细地址不能为空") }]
            })(
              <TextArea rows={2} />
            )}
          </FormItem>
        </Form>
      </Modal>
    )
  }
};
const DrugDeliveryAddressForm = Form.create()(DrugDeliveryAddress);
export default DrugDeliveryAddressForm;