// 分配点评任务
import React from 'react';
import { Card, Row, Col, Form, DatePicker, Select, Button, Modal, Table, Switch, message, Pagination, Input, Checkbox, Icon } from 'antd';
import { $http } from 'containers/config/https';
import Moment from 'moment';
import store from 'store';
import './style/index.less';
import {printStkPay} from '../commonPrint/stkPrint';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import CommonPagination from 'components/pagination/index';

const { Option } = Select;
const FormItem = Form.Item;
const formItemLayout = {    // label 和input宽度
    labelCol: { span:8 },
    wrapperCol: { span: 16 },
};

const PaymentManagement = Form.create()(
    class extends React.Component {
        constructor() {
            super();
            this.state = {
                userInfo: JSON.parse(window.sessionStorage.userData),
                data: [],
                queryCondition: {},
                inOpLocDr:'',
                vendor: '',
                detailsId: '',//付款单ID
                detailsListData:[], //明细数据
                ReviewsData: [], //点评单据
                userData: [], //点评人
                size: 'small',
                pageSize: 20,
                page: 1,
                pageSize2: 20,
                page2: 1,
                total:0,
                detailTotal: 0,
                show: false,
                paymentID: '',
                modalColumns: [],
                detailWidthTotal: '',
                ChineseEnglishSize: [],
                columns:[],
                columnsWidth:'',
                uncomData: {},
                valueID: '', //输入框行id
                valueData: '', //输入框数据
            };

            // 药品的数据表头
            this.columns = [
                {
                    key: 1,
                    title: '点评单号',
                    dataIndex: 'reviewNo',
                    align: "center",
                    width: '100px'
                },
                {
                    key: 2,
                    title: '点评单类型',
                    dataIndex: 'way',
                    align: "center",
                    width: '100px'
                },
                {
                    key: 3,
                    title: '日期',
                    dataIndex: 'createDate'
                    ,
                    align: "center",
                    width: '100px'
                },   {
                    key: 4,
                    title: '时间',
                    dataIndex: 'createTime',
                    align: "center",
                    width: '100px'
                },
                {
                    key: 5,
                    title: '制单人',
                    dataIndex: 'createUser',
                    align: "center",
                    width: '100px'
                },
                {
                    key: 6,
                    title: '所抽处方总数量',
                    dataIndex: 'count',
                    align: "center",
                    width: '100px'
                },
                {
                    key: 7,
                    title: '未分配处方数',
                    dataIndex: 'uncom',
                    align: "center",
                    width: '100px'
                }
            ];
            // 付款单详细表头
            this.modalColumns = [
                {
                    key: 1,
                    title: '点评人',
                    dataIndex: 'userName',
                    align: "center",
                    width: '50%'
                },
                {
                    key: 8,
                    title: '数量',
                    dataIndex: 'preCount',
                    align: "center",
                    width: '50%'
                }
            ];
            this.columnsL = [
                {
                    key: 1,
                    title: '药师姓名',
                    dataIndex: 'userName',
                    align: "center",
                    width: '50%'
                },
                {
                    key: 8,
                    title: '药师需要点评的处方数量',
                    dataIndex: 'num',
                    align: "center",
                    width: '50%',
                    render: (text, record) => {
                        return( <Input min={0} type="number" value={record.num}  style={{ float: 'left',  marginLeft: '6px', width: '70%',padding: '0', paddingLeft: '5px'}} onChange={(g)=> {this.handleField(g ,'num',record.userID)}} />)
                    },
                }
            ]
        }

        componentDidMount() {
            // 初始化数据
            this.getDetailTableColumns();
            this.getColumnsLeft();
            let leftList = document.querySelectorAll('.waListHeight  .ant-table-body');
            if(leftList.length>0){
                leftList[0].style.height = (store.getState().tableHeight.y)/2 -20 + 'px';
            }
            let listData = document.querySelectorAll('.detailsHeight  .ant-table-body');
            if(listData.length>0){
                listData[0].style.height = store.getState().tableHeight.y + 82 + 'px';
            }
            let TasksList = document.querySelectorAll('.TasksHeight  .ant-table-body');
            if(TasksList.length>0){
                TasksList[0].style.height = (store.getState().tableHeight.y)/2 -20  + 'px';
            }
        }
        // 获取明系列表头数据
        getDetailTableColumns = () => {
            let {userInfo} = this.state;
            let data = {
                params: [{
                    reactCode: ['PaymentManagement'],
                    compontName: 'PaymentManagementList',
                    type: 'C',
                }]
            }
            $http.post('urlS', this, {
                code: '01040073',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        let arr = res.result.C&&res.result.C.length > 0 ? JSON.parse(JSON.stringify(res.result.C)).map((item, index) => {
                            return  {
                                ...item,
                                key: index + 1,
                                title: <div onDoubleClick={() => { this.columnRef.onOpenModel();}}>{userInfo.language== 'EN' ? item.enDescripts : item.title}</div>
                            }
                        }) : '';
                        let filterArr = arr.filter(function(item){ return item.display === 'Y'});
                        // this.setState({modalColumns: filterArr, detailWidthTotal: res.totalWidth,ChineseEnglishSize:userInfo.language=='EN' ? res.result.language.EN : res.result.language.CN})
                    }
                }
            });
        };

        //页面中英文翻译
        getColumnsLeft = () => {
            let {userInfo} = this.state;
            let data = {
                params: [{
                    compontName: 'DrugPaymentManagementLeftColum',
                    type: 'C',
                }]
            }
            $http.post('urlS', this, {
                code: '01040073',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        let arr = res.result.C&&res.result.C.length > 0 ? JSON.parse(JSON.stringify(res.result.C)).map((item, index) => {
                            return  {
                                ...item,
                                key: index + 1,
                                title: <div>{userInfo.language== 'EN' ? item.enDescripts : item.title}</div>
                            }
                        }) : '';
                        let filterArr = arr.filter(function(item){ return item.display === 'Y'});
                        // this.setState({columns: filterArr, columnsWidth: res.totalWidth})
                    }
                }
            })
        };
        //获取操作行数据对象
        getRowByKey(key, newData) {
            const { userData } = this.state;
            return (newData || userData).filter(item => item.userID === key)[0];
        }

        //文本框数据修改
        handleField=(e, fieldName, key)=>{
            if(this.state.uncomData.uncom && this.state.uncomData.uncom < e.target.value){
                message.error('输入不能大于未分配处方数');
                return
            }
            const { userData} = this.state;
            const newData = userData.map(item => ({ ...item }));
            const target = this.getRowByKey(key, newData);
            if (target) {
                target[fieldName] = e.target.value;
                this.setState({userData: newData});
            }
        };

        //清空表格内容
        handleReset = () => {
            this.setState({ReviewsData: [],detailsListData: [],total: 0, detailsId: ''});
            this.props.form.setFieldsValue({stockDr: undefined});
            this.props.form.resetFields();
        };
        handleFieldChange=()=>{
         if(!this.state.detailsId){
             message.error('请选择点评单据')
             return
         }
         // if(this.state.uncomData.uncom && this.state.uncomData.uncom > this.state.ValueData){
             let data = {
                 params: [{
                     preID: this.state.detailsId,

                     paraArr:this.state.userData
                 }],
             };
             $http.post('urlS', this, {
                 code: "02020351",
                 data: data,
                 success: function (res) {
                     if(res.errorCode == 0){
                         message.success(res.errorMessage);
                         this.getDetailList();
                         this.getWarehouseList();
                     }
                 }
             });
         // }else {
         //     message.error('输入不能大于未分配处方数')
         // }

        }
        //获取输入框值和id
        valueData=(v, id)=>{
            this.setState({
                ValueID:id,
                ValueData: v.target.value
            })
        }
        // 获取点评单列表数据
        getWarehouseList=(num)=>{
            let {ChineseEnglishSize} = this.state;
            let EndData = this.props.form.getFieldValue('EndData');
            let StartDate = this.props.form.getFieldValue('StartDate');
            this.setState({ValueData:'', ValueID: ''});
            let data = {
                params: [{
                    startDate: Moment(StartDate).format('YYYY-MM-DD'),
                    endDate: Moment(EndData).format('YYYY-MM-DD'),
                }],
                // pagination: [
                //     {
                //         pageSize:this.state.pageSize,
                //         currentPage:this.state.page,
                //         sort:"ID",
                //         dir:"asc",
                //     }
                // ],
            };
            $http.post('urlS', this, {
                code: "02020349",
                data: data,
                success: function (res) {
                    if(res.review.length > 0){
                        for(var i = 0; i < res.review.length; i++){
                            res.review[i].key = i;
                        }
                        this.setState({ ReviewsData: res.review, userData: res.user});
                        // this.getWarehouseEntryDetails(res.review[0].stkLocID)
                    }else {
                        this.setState({ReviewsData: [], detailsListData: [],});
                        if(num !== '1'){
                            message.error(ChineseEnglishSize.PaymentManagementnoData ? ChineseEnglishSize.PaymentManagementnoData.descripts:"没数据")
                        }
                    }
                },
                error: function (err) {
                    message.error(err.errorMessage)
                }
            });
        };
        // 获取点评单列表数据
        getDetailList=(num)=>{
            let {ChineseEnglishSize} = this.state;
            let data = {
                params: [{
                    preID: this.state.detailsId,
                }],
                pagination: [
                    {
                        pageSize:this.state.pageSize,
                        currentPage:this.state.page,
                        sort:"ID",
                        dir:"asc",
                    }
                ],
            };
            $http.post('urlS', this, {
                code: "02020350",
                data: data,
                success: function (res) {
                    if(res.data.length > 0){
                        for(var i = 0; i < res.data.length; i++){
                            res.data[i].key = i;
                        }
                        this.setState({ detailsListData: res.data,total: res.total});
                        // this.getWarehouseEntryDetails(res.data[0].stkLocID)
                    }else {
                        this.setState({ detailsListData: [],});
                        if(num !== '1'){
                            message.error(ChineseEnglishSize.PaymentManagementnoData ? ChineseEnglishSize.PaymentManagementnoData.descripts:"没数据")
                        }
                    }
                }
            });
        };

        // complete=()=>{
        //     const {record}=this.state;
        //     let post={};
        //     if (record.stateID==10){
        //         post.code='02020241';
        //     }else if(record.stateID==20){
        //         post.code='02020242';
        //     }else{
        //         return;
        //     }
        //     post.data={
        //         params:[{
        //             stkPayID:record.stkPayID
        //         }]
        //     }
        //     $http.post('urlS', this, {
        //         ...post,
        //         success: function (res) {
        //             if (res.errorCode==0){
        //                 message.success(res.errorMessage);
        //                 this.getWarehouseList('1');
        //                 this.setState({paymentID:'',record:{}});
        //             }else{
        //                 message.error(res.errorMessage);
        //             }
        //         },
        //         error: function (err) {
        //             message.error(err.errorMessage)
        //         }
        //     });
        // }


        //点击行，渲染当前行样式
        setRowClassName = (record) => {
            if(record){
                if(this.state.detailsId == record.id) return 'clickRowStyle';
                else return '';
            }else {
                return '';
            }
        };
        setPaymentClassName= (record) => {
            if(record){
                if(this.state.paymentID == record.stkPayID) return 'clickRowStyle';
                else return '';
            }else {
                return '';
            }
        };

        // 页码改变的回调，参数是改变后的页码及每页条数
        onChange = (e) => {
            this.setState({page: e, pageSize: this.state.pageSize}, () => {
                // 重新调用查询方法
                this.getWarehouseList();
            });
        };
        // 显示分页总条数
        showTotal(total) {
            return `共 ${total} 条`;
        }
        onShowSizeChange = (current, size) => {
            this.setState({page: current, pageSize: size}, () => {
                // 重新调用查询方法
                this.onChange(current,size);
            })
        };


        onRef = (ref) => {
            this.childModal = ref;
        };

        //组件权限编辑器
        onColumnRef = (ref) => {
            this.columnRef = ref;
        };

        render() {
            const { getFieldDecorator } = this.props.form;
            let {ChineseEnglishSize,columns,modalColumns,userInfo} = this.state;
            return (
                <div className="paymentManagement">
                    <Row>
                        <Col span={11}>
                            <Card
                                size="small"
                                title={<div className="card-title-left-icon"><div></div>{ChineseEnglishSize.PaymentManagementsupplier ? ChineseEnglishSize.PaymentManagementsupplier.descripts:'查询点评单'}</div>}
                            >
                                <Col>
                                    <Form>
                                        <Row >
                                            <Col span={7}>
                                                <FormItem {...formItemLayout} label={ChineseEnglishSize.InventoryAlarmAccordingToConsuStartDate ? ChineseEnglishSize.InventoryAlarmAccordingToConsuStartDate.descripts:'起初日期'}>
                                                    {getFieldDecorator('StartDate',{
                                                        initialValue: Moment(),
                                                        rules: [{required: false, message: '起初日期不能为空',}],
                                                    })(
                                                        <DatePicker format="YYYY-MM-DD" style={{width:'100%'}}/>
                                                    ) }
                                                </FormItem>
                                            </Col>
                                            <Col span={7}>
                                                <FormItem {...formItemLayout} label={ChineseEnglishSize.InventoryAlarmAccordingToConsudeadline ? ChineseEnglishSize.InventoryAlarmAccordingToConsudeadline.descripts:'截止日期'}>
                                                    {getFieldDecorator('EndData',{
                                                        initialValue: Moment(),
                                                        rules: [{required: false, message: '截止日期不能为空',}],
                                                    })(
                                                        <DatePicker  format="YYYY-MM-DD" style={{width:'100%'}}/>
                                                    ) }
                                                </FormItem>
                                            </Col>
                                            <Col span={3}  style={{marginLeft: '30px'}}>
                                                <Row style={{marginTop: '4px'}} className="buttonLeft">
                                                    <Button onClick={this.getWarehouseList}>{ChineseEnglishSize.PaymentManagementsearch ? ChineseEnglishSize.PaymentManagementsearch.descripts:'查询'}</Button>
                                                </Row>
                                            </Col>
                                        </Row>
                                    </Form>
                                </Col>
                                <div className="drugList ">
                                    <Table
                                        columns={this.columns}
                                        dataSource={this.state.ReviewsData.length>0 ? this.state.ReviewsData : []}
                                        pagination={false}
                                        bordered
                                        scroll={{ x: 700, y: (store.getState().tableHeight.y)/2}}
                                        rowClassName={this.setRowClassName}
                                        rowKey={record => record.key}
                                        className='TasksHeight'
                                        onRow={(record) => {
                                            return {
                                                onClick: (e) => {
                                                    e.stopPropagation();
                                                    this.setState({ValueData:'', ValueID: ''})
                                                    if (this.state.detailsId === '') {
                                                        // 保存行数据以及ID
                                                        this.setState({detailsId: record.id, page: 1 ,uncomData: record },()=>{
                                                            this.getDetailList()
                                                        });

                                                    } else {
                                                        if (this.state.detailsId !== record.id) {
                                                            this.setState({detailsId: record.id, page: 1, uncomData: record },()=> {
                                                                this.getDetailList()
                                                            });
                                                        } else {
                                                            this.setState({detailsId: '', uncomData: {}});
                                                        }
                                                    }
                                                },

                                            };
                                        }}
                                    />
                                </div>
                            </Card>
                            <Card
                                size="small"
                                title={<div className="card-title-left-icon"><div></div>{ChineseEnglishSize.PaymentManagementsupplier ? ChineseEnglishSize.PaymentManagementsupplier.descripts:'分配点评任务'}<span> <Button onClick={()=>{this.handleFieldChange()}} style={{ marginLeft: '20px'}} disabled={this.state.userData.length>0 ? false : true}>保存</Button></span></div>}
                            >
                                <div className="drugList2 ">
                                    <Table
                                        columns={this.columnsL}
                                        dataSource={this.state.userData.length>0 ? this.state.userData : []}
                                        pagination={false}
                                        bordered
                                        scroll={{ x: '100%', y: (store.getState().tableHeight.y)/2}}
                                        rowKey={record => record.key}
                                        className='waListHeight'
                                    />
                                </div>
                            </Card>
                        </Col>
                        <Col span={13}>
                            <Card
                                size="small"
                                title={<div className="card-title-left-icon"><div></div>{ChineseEnglishSize.PaymentManagementsupplier ? ChineseEnglishSize.PaymentManagementsupplier.descripts:'点评任务分配明细'}</div>}
                                extra={<span style={{color: '#666'}} className='span' onClick={() => { this.columnRef.onOpenModel();}}><Icon type="setting" title={ChineseEnglishSize.PaymentManagementcolumnSettings ? ChineseEnglishSize.PaymentManagementcolumnSettings.descripts:'列权限设置'} /></span>}
                            >
                                <div>
                                    <Table
                                        columns={this.modalColumns}
                                        dataSource={this.state.detailsListData}
                                        pagination={false}
                                        bordered
                                        scroll={{x: '100%', y: store.getState().tableHeight.y + 81 }}
                                        rowKey={record => record.key}
                                        className='detailsHeight'
                                    />
                                    <CommonPagination size={this.state.size} current={this.state.page} total={this.state.total} search= 'search'
                                                      onShowSizeChange={this.onShowSizeChange.bind(this)} complete={true} dataSource={this.state.detailsListData}
                                                      loading={this.state.loading} onChange={this.onChange.bind(this)} pageSize={true} />
                                </div>
                            </Card>
                        </Col>
                    </Row>

                    {/*//显示表头修改弹窗*/}
                    <ColumnAuthoritysModel
                        clientWidth='800px'
                        compontName='PaymentManagementList'
                        configType="C"
                        onRef={this.onColumnRef}
                        reloadData={this.getDetailTableColumns}
                    />
                </div>
            )
        }
    }
);
export default PaymentManagement;