/*
 * Creator:     ML
 * CreatDate:   2020-03-12
 * descripts：  患者中心 录入申请单  查看 修改(砍掉)
 * */
// 添加就诊人
import React from 'react';
import { InputItem, Toast, Picker, List } from 'antd-mobile';
import { createForm } from 'rc-form';
import { $http } from "containers/config/https";
// import { Util } from 'tools';
import './style/index.less';
import moment from 'moment';
import store from "store";
const Item = List.Item
class ApplyOrder extends React.Component {
    constructor({ history }) {
        super();
        let userData = localStorage.getItem("userData") ? JSON.parse(localStorage.getItem("userData")) : {};
        this.state = {
            userData,
            errorData: {},
            number: 1,
            frequence: 1,//每天次数
            ordDose: 1,//每次数量
            durQty: 1,//疗程天数
            admVisible: false,
            frequencyID: "",
            count: 0,
        };
        this.history = history;
    }

    componentDidMount = () => {
        if (store.getState().homeRedux && store.getState().homeRedux.treatmentItemsData && store.getState().homeRedux.treatmentItemsData.count) {
            this.setState({
                count: store.getState().homeRedux && store.getState().homeRedux.treatmentItemsData && store.getState().homeRedux.treatmentItemsData.count,
                frequencyID: store.getState().homeRedux && store.getState().homeRedux.treatmentItemsData && store.getState().homeRedux.treatmentItemsData.ordFreqID,
                durQty: store.getState().homeRedux && store.getState().homeRedux.treatmentItemsData && store.getState().homeRedux.treatmentItemsData.durQty,
            }, () => {
                this.getFrequence()
            })
        } else {
            this.getFrequence()
        }
    }
    componentWillUnmount() {
        // 组件销毁前将静止让setState修改state的状态
        this.setState = (state, callback) => { return; }
    }

    // 计算总数量 频次
    handleVerification = (type, e) => {
        this.setState({
            [type]: e.toString()
        }, () => {
            this.handleTotalPatPrice()
        })
    }
    //计算总数量
    handleTotalPatPrice = () => {
        let data = {
            params: [{
                ordFreqID: this.state.frequencyID || "",
                durQty: this.state.durQty || ""
            }],
        }
        $http.post("urlS", this, {
            code: "01040017",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    this.setState({
                        count: res.result.count
                    })
                }
            }
        });
    }
    // 点击显示错误信息
    onErrorClick = (key) => {
        let { errorData } = this.state;
        if (errorData[key]) {
            let errorMessage = errorData[key].errors[0].message;
            Toast.info(errorMessage);
        }
    }
    // 验证成功去除验证警告
    removeWarning = (key) => {
        let obj = JSON.parse(JSON.stringify(this.state.errorData))
        obj[key] = false
        this.setState({ errorData: obj })
    }
    //获取频次
    getFrequence = () => {
        const { userData } = this.state
        // let obj = {};
        let data = {
            params: [{
                hospCode: userData && userData.hospCode ? userData.hospCode : "",
            }],
        }
        $http.post("urlS", this, {
            code: "01040015",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    let arr = []
                    for(var i = 0; i < res.result; i++) {
                        res.result[i]["id"] = Number(res.result[i].id)
                        res.result[i]["label"] = res.result[i].descripts
                        res.result[i]["value"] = Number(res.result[i].id)
                        this.setState({
                            frequencyData: res.result
                        })
                    }
                    // res.result && res.result.map((i, s) => {
                        
                    // })
                    //不是编辑  直接新增 默认选中第一个 查看
                    if (store.getState().homeRedux && store.getState().homeRedux.treatmentItemsData.edit !== 1) {
                        // console.log("store.getState().homeRedux.treatmentItemsData查看-----",store.getState().homeRedux.treatmentItemsData)
                        arr.push(res.result[0].id)
                        this.setState({
                            frequencyID: (store.getState().homeRedux && store.getState().homeRedux.treatmentItemsData.ordFreqID) || res.result[0].id,
                            frequencyArrID: arr,
                            // durQty:(store.getState().homeRedux && store.getState().homeRedux.treatmentItemsData.durQty) || 1,
                            // count:store.getState().homeRedux && store.getState().homeRedux.treatmentItemsData.count || 0,
                        }, () => {
                            this.handleTotalPatPrice()
                        })
                    } else {
                        //编辑拿对应的
                        let id = Number(store.getState().homeRedux && store.getState().homeRedux.treatmentItemsData.ordFreqID)
                        arr.push(id)
                        this.setState({
                            frequencyID: store.getState().homeRedux && store.getState().homeRedux.treatmentItemsData.ordFreqID,
                            frequencyArrID: arr,
                            // durQty:(store.getState().homeRedux && store.getState().homeRedux.treatmentItemsData.durQty) || 1,
                            // count:store.getState().homeRedux && store.getState().homeRedux.treatmentItemsData.count,
                        }, () => {
                            this.handleTotalPatPrice()
                        })
                    }
                }
            }
        });
    }
    // 选择就诊人
    handleAdmSelectChange = (val) => {
        let arr = [];
        arr["value"] = "";
        for (var i = 0; i < val.length; i++) {
            arr["value"] = Number(val[i])
        }
        // val && val.map((i, s) => {
        //     arr["value"] = Number(i)
        // })
        this.setState({ frequencyID: arr.value })
    }
    // 打开选择就诊人弹窗
    handleShowAdmModal = () => {
        this.setState({ admVisible: true })
    }

    // 关闭就诊人弹窗
    handleAdmClose = () => {
        this.setState({ admVisible: false, frequencyID: "" })
    }
    // 提交申请
    handleApply = () => {
        // console.log("this.state.frequencyID---",this.state.frequencyID)
        const { userData, frequencyData } = this.state;
        this.props.form.validateFields((error, values) => {
            if (!error) {
                let obj = store.getState().homeRedux && store.getState().homeRedux.treatmentItemsData
                obj["totalPrice"] = (store.getState().homeRedux && store.getState().homeRedux.treatmentItemsData && store.getState().homeRedux.treatmentItemsData.patPrice) * this.state.count
                obj["count"] = this.state.count
                obj["applyData"] = moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
                obj["durQty"] = this.state.durQty;
                for (var i = 0; i < frequencyData.length; i++) {
                    if (this.state.frequencyID === frequencyData[i].id) {
                        obj["frequenceDesc"] = frequencyData[i].descripts
                    }
                }
                // frequencyData && frequencyData.map((i, s) => {
                    
                // })
                //修改申请
                if (+store.getState().homeRedux && store.getState().homeRedux.treatmentItemsData.edit === 1) {
                    let data = {
                        params: [{
                            durQty: this.state.durQty || "",//疗程数 ---疗程天数
                            cureAppID: (store.getState().homeRedux && store.getState().homeRedux.treatmentItemsData && store.getState().homeRedux.treatmentItemsData.ID) || "",
                            projectNum: this.state.count || "",//治疗次数---总数量
                            ordFreqID: this.state.frequencyID || "",//频次次数,---每天次数
                        }]
                    }
                    $http.post("urlS", this, {
                        code: "01040013",
                        data: data,
                        success: function (res) {
                            if (+res.errorCode === 0) {
                                this.setState({
                                    cureAppID: res.cureAppID
                                }, () => {
                                    obj["cureAppID"] = this.state.cureAppID
                                    //修改 申请成功提示
                                    this.history.push({
                                        pathname: "/0002/0012",
                                        state: { ...obj }
                                    })
                                    store.dispatch({
                                        type: "treatmentItems",
                                        value: { ...obj }
                                    });
                                })
                            } else {
                                Toast.info(res.errorMessage)
                            }
                        },
                        error: function (error) {
                            Toast.info(error);
                        }
                    });
                } else {
                    let data = {
                        params: [{
                            hospCode: userData && userData.hospCode ? userData.hospCode : "",
                            locID: store.getState().homeRedux && store.getState().homeRedux.treatmentItemsData && store.getState().homeRedux.treatmentItemsData.locID,
                            patID: userData && userData.HISPatID ? userData.HISPatID : "",
                            medID: (store.getState().homeRedux && store.getState().homeRedux.treatmentItemsData.medID) || "",
                            durQty: this.state.durQty || "",//疗程数 ---疗程天数
                            projectNum: this.state.count || "",//治疗次数---总数量,
                            ordFreqID: this.state.frequencyID || "",//频次次数,---每天次数
                        }]
                    }
                    $http.post("urlS", this, {
                        code: "01040010",
                        data: data,
                        success: function (res) {
                            if (+res.errorCode === 0) {
                                this.setState({
                                    cureAppID: res.cureAppID
                                }, () => {
                                    obj["cureAppID"] = this.state.cureAppID
                                    //申请成功提示
                                    this.history.push({
                                        pathname: "/0002/0012",
                                        state: { ...obj }
                                    })
                                    store.dispatch({
                                        type: "treatmentItems",
                                        value: { ...obj }
                                    });
                                })
                            } else {
                                Toast.info(res.errorMessage)
                            }
                        },
                        error: function (error) {
                            Toast.info(error);
                        }
                    });
                }


            } else {
                this.setState({errorData: error})
            }
        });
    }

    render() {
        let { errorData } = this.state;
        const { getFieldProps } = this.props.form;
        return (
            <div className="apply-dom">
                <form>
                    <div>
                        <List>
                            <div className="title project-list">
                                <p>
                                    <span>{store.getState().homeRedux && store.getState().homeRedux.treatmentItemsData && store.getState().homeRedux.treatmentItemsData.descripts}</span>
                                    <span> <span style={{ color: "#3dc17f" }}>{store.getState().homeRedux && store.getState().homeRedux.treatmentItemsData && store.getState().homeRedux.treatmentItemsData.patPrice}</span>{"元/" + (store.getState().homeRedux && store.getState().homeRedux.treatmentItemsData && store.getState().homeRedux.treatmentItemsData.unit)}</span>
                                </p>
                                <p>
                                    <span>{(store.getState().homeRedux && store.getState().homeRedux.treatmentItemsData && store.getState().homeRedux.treatmentItemsData.locDesc) || "--"}</span>
                                </p>
                            </div>
                        </List>
                        <List>
                            {/* 修改 录入 */}
                            <div className={(store.getState().homeRedux && store.getState().homeRedux.treatmentItemsData && store.getState().homeRedux.treatmentItemsData.disabled) ? "listItem-none picker-dom" : "listItem-dom picker-dom"}>
                                <Picker data={this.state.frequencyData} cols={1}
                                    error={true}
                                    onErrorClick={() => this.onErrorClick("frequencyID")}
                                    title="频次"
                                    {...getFieldProps('frequencyID', {
                                        onChange: (e) => this.handleVerification("frequencyID", e),
                                        initialValue: this.state.frequencyArrID,
                                        rules: [
                                            { required: true, message: '请选择' },
                                        ],
                                        disabled: store.getState().homeRedux && store.getState().homeRedux.treatmentItemsData && store.getState().homeRedux.treatmentItemsData.disabled
                                    })}
                                >
                                    <List.Item disabled={true} arrow="horizontal">频次：</List.Item>
                                </Picker>
                            </div>
                            {/* 查看 */}
                            <div className={(store.getState().homeRedux && store.getState().homeRedux.treatmentItemsData && store.getState().homeRedux.treatmentItemsData.disabled) ? "listItem-dom" : "listItem-none"}>
                                <span className="header-right" style={{ padding: "12px 0 12px 46px", fontSize: "14px" }}><i className="iconfont " >频次：</i>{(store.getState().homeRedux && store.getState().homeRedux.treatmentItemsData && store.getState().homeRedux.treatmentItemsData.frequenceDesc)}</span>
                            </div>
                        </List>
                        <List>
                            <div className="listItem-dom">
                                <InputItem
                                    error={errorData.durQty ? true : false}
                                    onErrorClick={() => this.onErrorClick("durQty")}
                                    {...getFieldProps('durQty', {
                                        onChange: (e) => this.handleVerification("durQty", e),
                                        initialValue: (store.getState().homeRedux && store.getState().homeRedux.treatmentItemsData && store.getState().homeRedux.treatmentItemsData.durQty) || 1,
                                        rules: [
                                            { required: true, message: '请输入' },
                                        ],
                                    })}
                                    type="digit"
                                    disabled={store.getState().homeRedux && store.getState().homeRedux.treatmentItemsData && store.getState().homeRedux.treatmentItemsData.disabled}
                                >疗程天数:</InputItem>
                                <span>天</span>
                            </div>
                        </List>
                        <Item className="item-tips">
                            <span>总数量：<span style={{ color: "#3dc17f" }}>{this.state.count}{"个"}</span></span>
                            {/* <span style={{display:(store.getState().homeRedux && store.getState().homeRedux.treatmentItemsData.edit != 1?"none":"inline-block")}}>总数量：<span style={{ color: "#3dc17f" }}>{this.state.count }{"个"}</span></span> */}

                            {/* <span> 可预约： <span style={{ color: "#3dc17f" }}>{store.getState().homeRedux && store.getState().homeRedux.treatmentItemsData && store.getState().homeRedux.treatmentItemsData.appointmentNum}</span></span> */}
                        </Item>
                        <div className="bottom-bar">
                            <span>总金额：￥{(store.getState().homeRedux && store.getState().homeRedux.treatmentItemsData && store.getState().homeRedux.treatmentItemsData.patPrice) * this.state.count || (store.getState().homeRedux && store.getState().homeRedux.treatmentItemsData && store.getState().homeRedux.treatmentItemsData.totalPrice)}</span>
                            {/* <Button disabled={store.getState().homeRedux && store.getState().homeRedux.treatmentItemsData && store.getState().homeRedux.treatmentItemsData.disabled} onClick={this.handleApply}>提交申请</Button> */}
                            {/* #22a9a9 */}
                            <span style={{ background: (store.getState().homeRedux && store.getState().homeRedux.treatmentItemsData && store.getState().homeRedux.treatmentItemsData.disabled) ? "#e7e7e7" : "" }} onClick={(store.getState().homeRedux && store.getState().homeRedux.treatmentItemsData && store.getState().homeRedux.treatmentItemsData.disabled) ? "" : this.handleApply}>提交申请</span>
                        </div>
                    </div>
                </form>
            </div>
        )
    }
};
const ApplyOrderForm = createForm()(ApplyOrder);
export default ApplyOrderForm;