// 确认配药方式
import React from 'react';
import { Accordion, List, Checkbox, Button, Modal, Toast, ActivityIndicator } from 'antd-mobile';
import './style/index.less';
import ListCheckboxItem from './common/ListCheckboxItem.jsx';
import { $http } from "containers/config/https";
import { Util } from 'tools';

const Item = List.Item;
const CheckboxItem = Checkbox.CheckboxItem;

export default class ConfirmDeliveryMethod extends React.Component {
  constructor({ history }) {
    super();
    let deliveryAddress = sessionStorage.getItem("deliveryAddress") ? JSON.parse(sessionStorage.getItem("deliveryAddress")) : {}; // 配送地址
    let weChatParams = sessionStorage.getItem("weChatParams") ? JSON.parse(sessionStorage.getItem("weChatParams")) : {};
    let userData = localStorage.getItem("userData") ? JSON.parse(localStorage.getItem("userData")) : {};
    this.state = {
      userData,
      weChatParams,
      deliveryAddress,
      prescriptionData: [], // 原处方数据
      checkboxData: [],
      radioData: [
        { value: '1', label: '物流配送', desc: '快递送上门', checked: false },
        { value: '2', label: '自提', desc: '煎药完成后，系统通过公众号通知您来医院取药。', checked: false }
      ],
      activeRadio: '',
      visible: false,
      deliveryAddressListData: [],
      animating: false,
      selfAddress: {}
    };
    this.history = history;
  }

  componentDidMount() {
    let prescriptionData = this.props.location && this.props.location.state ? this.props.location.state : [];
    let prescriptionActiveRadio = sessionStorage.getItem("prescriptionActiveRadio") ? JSON.parse(sessionStorage.getItem("prescriptionActiveRadio")) : "";
    if (prescriptionData && prescriptionData.length > 0) {
      this.setState({ prescriptionData, activeRadio: prescriptionActiveRadio }, () => {
        this.filterCheckData();
        this.setTheWayOfTakingMedicine();
        window.sessionStorage.setItem(
          "prescriptionData",
          JSON.stringify(
            [...prescriptionData]
          )
        );
      })
    } else {
      let sessionPrescriptionData = sessionStorage.getItem("prescriptionData") ? JSON.parse(sessionStorage.getItem("prescriptionData")) : [];
      if (sessionPrescriptionData && sessionPrescriptionData.length > 0) {
        this.setState({ prescriptionData: sessionPrescriptionData, activeRadio: prescriptionActiveRadio }, () => {
          this.filterCheckData();
          this.setTheWayOfTakingMedicine();
        })
      } else {
        this.setState({ prescriptionData: [] })
      }
    }
  }

  // 修改
  getCheckboxData = (listData) => {
    this.setState({ prescriptionData: listData }, () => {
      this.filterCheckData();
    })
  }

  // 过滤出已勾选处方
  filterCheckData = () => {
    let { prescriptionData } = this.state;
    let newArr = [];
    for (let i = 0; i < prescriptionData.length; i++) {
      if (prescriptionData[i].checked) {
        newArr.push(prescriptionData[i])
      }
    }
    this.setState({ checkboxData: newArr })
  }

  // 设置取药方式状态
  setTheWayOfTakingMedicine = () => {
    let { activeRadio, radioData } = this.state;
    for (let i = 0; i < radioData.length; i++) {
      if (radioData[i].value === activeRadio) {
        radioData[i].checked = true;
        break;
      }
    }
    this.setState({ radioData }, () => {
      if (activeRadio === '2') {
        this.getSelfAddress()
      } else if (activeRadio === '1') {
        this.getDeliveryAddressListData();
      }
    })
  }

  // 切换取药方式
  handleRadioChange = (item) => {
    let { radioData, deliveryAddressListData } = this.state;
    let activeRadio = "";
    for (let i = 0; i < radioData.length; i++) {
      radioData[i].checked = false;
      if (radioData[i].value === item.value) {
        radioData[i].checked = true;
        activeRadio = radioData[i].value;
      }
    }
    this.setState({ radioData, activeRadio }, () => {
      window.sessionStorage.setItem(
        "prescriptionActiveRadio",
        JSON.stringify(
          this.state.activeRadio
        )
      );
      if (this.state.activeRadio === '1' && !(deliveryAddressListData && deliveryAddressListData.length > 0)) {
        this.getDeliveryAddressListData();
      } else if (this.state.activeRadio === '2') {
        this.getSelfAddress()
      }
    })
  }

  // 获取配送地址
  getDeliveryAddressListData = () => {
    let { weChatParams } = this.state;
    let data = {
      params: [{
        openID: weChatParams.openID || "",
        pubAccCode: weChatParams.pubAccCode || "",
      }]
    }
    $http.post("urlS", this, {
      code: "01020006",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          let resData = res.result && res.result.rows && res.result.rows.length > 0 ? res.result.rows : [];
          let deliveryAddress = this.state.deliveryAddress;
          if ((!(this.state.deliveryAddress && this.state.deliveryAddress.id)) && resData && resData.length > 0) {
            deliveryAddress = resData[resData.length - 1];
          }
          this.setState({ deliveryAddressListData: resData, deliveryAddress }, () => {
            // 获取配送费
          });
        } else {
          this.setState({ deliveryAddressListData: [] });
        }
      }
    });
  }

  // 修改配送地址
  handleChildItemClick = () => {
    this.setState({ visible: true });
  }

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

  // 选择配送地址
  handleSelectAddressClick = item => {
    this.setState({ animating: true })
    this.setState({ deliveryAddress: item, animating: false }, () => {
      window.sessionStorage.setItem(
        "deliveryAddress",
        JSON.stringify(
          { ...this.state.deliveryAddress }
        )
      );
      this.handleClose();
    })
  }

  // 添加配送地址
  handleAddAddress = () => {
    this.history.push({
      pathname: "/0001/00020015",
      state: {}
    });
  }

  // 修改地址
  handleModify = (item, e) => {
    e.stopPropagation(); // 阻止事件冒泡
    this.history.push({
      pathname: "/0001/00020015",
      state: { ...item }
    });
  }

  // 过滤处方号
  filterPrescriptionNo = () => {
    let { checkboxData } = this.state;
    let newArr = [];
    for (var i = 0; i < checkboxData.length; i++) {
      newArr.push(checkboxData[i].ordPrescNo)
    }
    return newArr;
  }

  // 查询处方接收科室地址
  getSelfAddress = () => {
    let { userData } = this.state;
    let data = {
      params: [{
        ordPrescNo: this.filterPrescriptionNo(),
        hospID: userData && userData.hisHospID ? userData.hisHospID : "",
      }]
    }
    $http.post("urlS", this, {
      code: "02030094",
      data: data,
      namespace: "HIS",
      success: function (res) {
        if (+res.errorCode === 0) {
          this.setState({ selfAddress: res.result })
        } else {
          Toast.info(res.errorMessage, 3, () => { }, false);
        }
      }
    });
  }

  // 提交确认
  handleSubmit = () => { // 自提 '', 物流 Y
    let { activeRadio, userData, deliveryAddress, checkboxData } = this.state;
    if (!(checkboxData && checkboxData.length > 0)) {
      Toast.info('请选择需要确认的处方。', 3, () => { }, false);
      return;
    }
    if (!activeRadio) {
      Toast.info('请选择取药方式。', 3, () => { }, false);
      return;
    }
    let data = {
      params: [{
        ordPrescNo: this.filterPrescriptionNo(),
        hospID: userData && userData.hisHospID ? userData.hisHospID : "",
        logisticsFlag: activeRadio === '1' ? 'Y' : '',
        consignee: deliveryAddress.name,
        telephone: deliveryAddress.mobile,
        provID: deliveryAddress.provinceID,
        cityID: deliveryAddress.cityID,
        areaID: deliveryAddress.areaID,
        villageID: deliveryAddress.villageID,
        address: deliveryAddress.address,
      }]
    }
    $http.post("urlS", this, {
      code: "02030095",
      data: data,
      namespace: "HIS",
      success: function (res) {
        Toast.info(res.errorMessage, 3, () => { }, false);
        if (+res.errorCode === 0) {
          window.sessionStorage.setItem(
            "confirmationOfDrugTaking",
            JSON.stringify(
              {
                checkboxData: [],
                activeTabs: "1"
              }
            )
          );
          this.history.go(-1);
        }
      }
    });
  }

  handleContact = e => {
    e.stopPropagation();
  }

  render() {
    let { prescriptionData, checkboxData, radioData, activeRadio, visible, deliveryAddressListData, deliveryAddress, selfAddress } = this.state;
    let checkboxDataLen = checkboxData instanceof Array ? checkboxData.length : 0;
    return (
      <div className="confirm-delivery-method">
        <Accordion className="cdm-accordion">
          <Accordion.Panel header={<span>已选处方 {checkboxDataLen}</span>}>
            <div className="codt-list">
              <List>
                <ListCheckboxItem history={this.history} listData={prescriptionData} getCheckboxData={this.getCheckboxData} />
              </List>
            </div>
          </Accordion.Panel>
        </Accordion>
        <div className="cdm-radio">
          <List renderHeader={() => '取药方式'}>
            {radioData && radioData.map((item, index) => (
              <CheckboxItem key={index} checked={item.checked} onChange={() => this.handleRadioChange(item)}>
                <div className="cdm-radio-context">
                  {item.label}
                  <p>{item.desc}</p>
                </div>
              </CheckboxItem>
            ))}
          </List>
        </div>
        {activeRadio === '1' ? (
          <div className="cdm-address">
            <List className="cdm-footer-list">
              <Item extra={<span style={{ color: "#0079FE" }} onClick={this.handleChildItemClick}>更改地址</span>}>收货地址</Item>
              <Item>
                <div>{deliveryAddress && deliveryAddress.name ? deliveryAddress.name : ''}<span style={{ marginLeft: '12px' }}>{deliveryAddress && deliveryAddress.mobile ? Util.phoneAddGap(deliveryAddress.mobile) : ''}</span></div>
                <div>
                  {deliveryAddress && deliveryAddress.provinceDesc ? deliveryAddress.provinceDesc : ''}
                  {deliveryAddress && deliveryAddress.cityDesc ? deliveryAddress.cityDesc : ''}
                  {deliveryAddress && deliveryAddress.areaDesc ? deliveryAddress.areaDesc : ''}
                  {deliveryAddress && deliveryAddress.villageDesc ? deliveryAddress.villageDesc : ''}
                  {deliveryAddress && deliveryAddress.address ? deliveryAddress.address : ""}
                </div>
              </Item>
            </List>
            <List className="cdm-footer-list">
              <Item extra={<span>到付</span>}>配送费</Item>
            </List>
          </div>
        ) : (activeRadio === '2' ? (
          <div className="cdm-address">
            <List className="cdm-footer-list">
              <Item>自提地址</Item>
              <Item>
                <div>
                  {selfAddress && selfAddress.locDesc ? selfAddress.locDesc : ''}
                  {selfAddress && selfAddress.build ? selfAddress.build : ''}
                  {selfAddress && selfAddress.floor ? selfAddress.floor + '层' : ''}
                  {selfAddress && selfAddress.locPhone ? (
                    <a style={{marginLeft: '12px'}} href={`tel:${selfAddress.locPhone}`} onClick={this.handleContact} alt="电话">{selfAddress.locPhone}</a>
                  ) : ''}
                </div>
                <div>
                  {selfAddress && selfAddress.province ? selfAddress.province : ''}
                  {selfAddress && selfAddress.city ? selfAddress.city : ''}
                  {selfAddress && selfAddress.floor ? selfAddress.floor : ''}
                  {selfAddress && selfAddress.area ? selfAddress.area : ''}
                  {selfAddress && selfAddress.village ? selfAddress.village : ''}
                  {selfAddress && selfAddress.address ? selfAddress.address : ''}
                </div>
              </Item>
            </List>
          </div>
        ) : "")}
        <div className="cdm-btn">
          <Button type="primary" onClick={this.handleSubmit}>提交确认</Button>
        </div>
        <Modal
          popup
          visible={visible}
          onClose={this.handleClose}
          animationType="slide-up"
          className="id-address-modal"
        >
          <List renderHeader={() => <div>选择配送地址<span className="close" onClick={this.handleClose}>关闭</span></div>} className="di-popup-list">
            {deliveryAddressListData && deliveryAddressListData.map((item, index) => (
              <List.Item onClick={() => this.handleSelectAddressClick(item)} key={index} extra={<i onClick={(e) => this.handleModify(item, e)} className="iconfont icon-bianji"></i>} thumb={<span className={deliveryAddress && (deliveryAddress.id === item.id) ? "check-pat radio-checked" : "check-pat"}></span>}>
                <div className="di-popup-list-childiten">
                  <p><span>{item.name}</span>{item.mobile}</p>
                  <p>{item.provinceDesc + item.cityDesc + item.areaDesc + item.villageDesc + item.address}</p>
                </div>
              </List.Item>
            ))}
            <List.Item className="dl-btn">
              <Button type="primary" onClick={this.handleAddAddress}>添加配送地址</Button>
            </List.Item>
          </List>
        </Modal>
        <ActivityIndicator
          toast
          text="资源加载中..."
          animating={this.state.animating}
        />
      </div>
    )
  }
}