/*
 * Creator:     HLH
 * CreatDate:   2020-3-10
 * descripts：  快递付款方式
 * */
import React from 'react';
import { Select, Row, Col, Button, Spin, Divider, Popconfirm, DatePicker, Icon, Input, Table, Modal, message, Form } from 'antd';
import { $http } from '../../containers/config/https';
import store from 'store';
import moment from 'moment';
import 'assets/css/common.css';
import DecoctingOrderModal from "../orderdiatemplet/component/DecoctingOrderModal"
import CommonPagination from 'components/pagination';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';

const FormItem = Form.Item;
const paddRightCol = {
    paddingRight: "0px"
}
const formItemLayout = {
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
}
let user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
const ExpressPayment = Form.create()(
    class ExpressPayment extends React.Component {
        constructor(props) {
            var userData = JSON.parse(sessionStorage.getItem('userData'));
            super(props);
            this.state = {
                userData: userData,
                //id
                ID: undefined,
                // 表格数据
                tableData: [],
                // 表格数据总条数
                total: 0,
                page: 1,
                pageSize: 10,
                size: "small",
                search: "",
                code: "",
                descripts: "",
                visible: false,
                num: -1,
                params: {},
                columns: [],
                localeProvider: []
            };
        }
        componentDidMount() {
            // 初始化列表数据
            this.handleQuery();
            document.querySelector(".table-body-height .ant-table-body").style.height = store.getState().tableHeight.y + 100 + 'px';
            document.querySelector(".table-body-height .ant-table-body").style.maxHeight = store.getState().tableHeight.y + 100 + 'px';
            this.getMainTableColumns();
        }
        // 查询
        handleQuery = () => {
            this.setState({ page: 1, pageSize: this.state.pageSize }, () => {
                let { code, descripts } = this.state;
                this.getTableData(code, descripts)
            })
        }
        // 请求列表数据
        getTableData(code, descripts) {
            let { page, pageSize } = this.state
            let data = {
                params: [{
                    code: code,
                    descripts: descripts
                }],
                pagination: [{
                    pageSize: pageSize,
                    currentPage: page
                }]
            }
            $http.post('urlS', this, {
                code: "03030046",
                data: data,
                success: function (res) {
                    if (res.errorCode == 0) {
                        this.setState({ tableData: res.result.data, total: res.result.totalCount })
                    } else {
                        this.setState({ tableData: [], total: 0 })
                    }
                },
                error: function (error) {
                    this.setState({
                        tableData: [], total: 0
                    })
                }
            })
        }
        // 改变描述
        onChangeDescripts = (e) => {
            this.setState({ descripts: e.target.value });
        }
        // 改变代码
        onChangeCode = (e) => {
            this.setState({ code: e.target.value })
        }
        //控制模态框显示
        closeModal = (bool) => {
            this.setState({ visible: bool, });
        }
        //删除 
        toggleEditable = (record) => {
            let datas = {}
            datas = {
                params: [{
                    updateUserID: JSON.parse(sessionStorage.userData).userID || '',
                    ID: record.ID,
                }],
            }
            $http.post('urlS', this, {
                code: '03030048',
                data: datas,
                success: function (res) {
                    if (res.errorCode == 0) {
                        message.success("删除成功");
                        this.handleQuery()
                    }
                }
            })
        }
        //更新
        handleCompile = (num, record) => {
            this.props.form.resetFields();
            this.setState({
                num: num,
                params: num == "1" ? record : "",
                visible: true
            })
        }
        save = () => {
            this.props.form.validateFields((err, values) => {
                const { params } = this.state
                if (!err) {
                    let data = {
                        params: [{
                            ID: params && params.ID ? params.ID : "",
                            descripts: values && values.descripts ? values.descripts : "",
                            code: values && values.code ? values.code : "",
                            eNDesc: values && values.eNDesc ? values.eNDesc : "",
                            seqNo: values && values.seqNo ? values.seqNo : "",
                            startDate: values.startDate ? moment(values.startDate).format('YYYY-MM-DD') : undefined,
                            stopDate: values.stopDate ? moment(values.stopDate).format('YYYY-MM-DD') : '',
                            updateUserID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).userID : ""
                        }]
                    }
                    $http.post("urlS", this, {
                        code: "03030047",
                        data: data,
                        success: function (res) {
                            if (res.errorCode == 0) {
                                // console.log(params)
                                if (params && params.ID) {
                                    message.success("修改成功")
                                    this.handleQuery();
                                    this.closeModal(false)
                                } else {
                                    message.success("新增成功")
                                    this.handleQuery();
                                    this.closeModal(false)
                                }
                            } else {
                                message.error('失败：' + res.errorMessage);
                            }
                        },
                        error: function (error) {
                            message.error('失败：' + error);
                        }
                    })
                } else {
                }
            })
        }
        //子组件 
        OnChildrefs = (ref) => {
            this.child = ref
        }
        // 修改page和pageSize 跳转至---
        onChange = (e) => {
            this.setState({ page: e, pageSize: this.state.pageSize, }, () => {
                // 重新调用查询方法
                let { code, ID, descripts } = this.state;
                this.getTableData(code, ID, descripts);
            })
        }
        //下拉选择页数
        onShowSizeChange = (page, pageSize) => {
            this.setState({ page: 1, pageSize: pageSize, search: "search" }, () => {
                // 重新调用查询方法
                let { code, ID, descripts } = this.state;
                this.getTableData(code, ID, descripts)
            })
        }
        // 显示分页总条数
        showTotal(total) {
            return `共 ${total} 条`;
        }
        //动态表头
        onColumnRef = (ref) => {
            this.columnRef = ref;
        }
        //国际化
        setMessage(name, message) {
            return this.state.localeProvider ? this.state.localeProvider[name][message] : ''
        }
        // 获取主列表columns
        getMainTableColumns = () => {
            let data = {
                params: [{
                    compontName: "PayMethod",
                    reactCode: ['PayMethod'],
                    type: 'C',
                }]
            }
            $http.post('urlS', this, {
                code: '01040073',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        let arr = res.result && res.result.C.length > 0 ? JSON.parse(JSON.stringify(res.result.C)).map(item => {
                            return {
                                align: item.align,
                                widthNum: parseInt(item.width),
                                width: item.width,
                                dataIndex: item.dataIndex,
                                title: <div onDoubleClick={() => this.columnRef.onOpenModel()}>{this.state.userData.language == 'EN' ? item.enDescripts : item.title}</div>,
                                display: item.display,
                                key: item.seqNo,
                            }
                        }) : '';
                        let filterArr = arr.filter(function (item) { return item.display === 'Y' });
                        this.setState({
                            columns: filterArr, widthTotal: res.totalWidth, localeProvider: this.state.userData.language == 'EN' ? res.result.language.EN : res.result.language.CN
                        })
                        let seqArr = {
                            align: "center",
                            widthNum: 140,
                            width: "150px",
                            code: "edit",
                            dataIndex: "edit",
                            title: this.state.localeProvider && this.state.localeProvider.PayMethodOperating ? this.setMessage('PayMethodOperating', 'descripts') : "操作：",
                            display: "Y",
                            render: (value, row, index) => {
                                return (
                                    <span>
                                        <span className='span' onClick={() => this.handleCompile("1", row)}>{this.state.localeProvider && this.state.localeProvider.PayMethodEdit ? this.setMessage('PayMethodEdit', 'descripts') : "编辑："}</span>
                                        <Divider type="vertical" />
                                        <Popconfirm title="是否要删除此行" onConfirm={() => this.toggleEditable(row)}>
                                            <a style={{ color: "red" }} >{this.state.localeProvider && this.state.localeProvider.PayMethodDelete ? this.setMessage('PayMethodDelete', 'descripts') : "删除："}</a>
                                        </Popconfirm>
                                    </span>
                                )
                            },
                        }
                        filterArr.push(seqArr)
                        this.setState({ columns: filterArr, widthTotal: res.totalWidth })
                    }
                }
            })
        }
        render() {
            // 组件所需参数
            const param = {
                // 表格数据
                data: this.state.tableData,
                // 数据总条数
                total: this.state.total,
                // 当前页数
                page: this.state.page,
            }
            const { getFieldDecorator } = this.props.form;
            const { params, columns } = this.state
            return (
                <div>
                    <div className="department-header">
                        <Row style={{ minHeight: '64px', padding: '0 24px' }}>
                            <Col span={18}>
                                {this.state.localeProvider && this.state.localeProvider.PayMethodDescripts ? this.setMessage('PayMethodDescripts', 'descripts') : "付款方式：  "}: <Input placeholder="请输入" style={{ width: '150px', margin: '23px 15px 0 0' }} onChange={this.onChangeDescripts} />
                                {this.state.localeProvider && this.state.localeProvider.PayMethodCode ? this.setMessage('PayMethodCode', 'descripts') : "代码："}：<Input placeholder="请输入" style={{ width: '150px', margin: '23px 15px 0 0' }} onChange={this.onChangeCode} />

                                <Button onClick={this.handleQuery} style={{ margin: '23px 15px 20px 0', background: 'rgba(255,255,255,1)' }}>{this.state.localeProvider && this.state.localeProvider.PayMethodInquire ? this.setMessage('PayMethodInquire', 'descripts') : "查询："}</Button>
                            </Col>
                            <Col span={6} style={{ textAlign: 'right' }}>
                                <Button icon="plus" onClick={() => this.handleCompile()} style={{ background: 'rgba(247,128,93,1)', color: '#fff', margin: '23px 15px 0 0' }}>{this.state.localeProvider && this.state.localeProvider.PayMethodAdd ? this.setMessage('PayMethodAdd', 'descripts') : "新增："}</Button>
                            </Col>
                        </Row>
                    </div>
                    <div style={{ widht: '100%', height: '10px', background: '#f0f2f5' }}></div>
                    <div style={{ padding: 24 }} className="table-body-height">
                        <Table
                            columns={columns}
                            dataSource={param.data}
                            pagination={false}
                            bordered
                            style={{ height: store.getState().tableHeight.y + 68 + 'px' }}
                        />
                        <CommonPagination size={this.state.size} page={this.state.page} current={this.state.page} total={this.state.total} search={this.state.search}
                            onShowSizeChange={this.onShowSizeChange.bind(this)} complete={true} dataSource={param.data}
                            onChange={this.onChange.bind(this)} />
                        <ColumnAuthoritysModel
                            clientWidth='800px'
                            compontName='PayMethod'
                            configType="C"
                            onRef={this.onColumnRef}
                            reloadData={this.getMainTableColumns}
                        />
                        <Modal
                            title={this.state.num == "1" ? "编辑快递付款方式" : "新增快递付款方式"}
                            visible={this.state.visible}
                            onOk={() => this.closeModal(false)}
                            onCancel={() => this.closeModal(false)}
                            width={1200}
                            footer={[
                                <Button key="submit" type="primary" loading={this.setState.loading} disabled={this.state.rowId == ""} onClick={this.save}>{this.state.localeProvider && this.state.localeProvider.PayMethodDetermine ? this.setMessage('PayMethodDetermine', 'descripts') : "确定："}</Button>,
                                <Button key="cancel" type="primary" loading={this.setState.loading} onClick={() => this.closeModal(false)}>{this.state.localeProvider && this.state.localeProvider.PayMethodCancel ? this.setMessage('PayMethodCancel', 'descripts') : "取消："}</Button>,
                            ]}
                        >
                            <div className="department-header">
                                <Form>
                                    <Row gutter={60} style={{ margin: '0' }}>
                                        <Col span={8} style={paddRightCol}>
                                            <FormItem {...formItemLayout} label={this.state.localeProvider && this.state.localeProvider.PayMethodDescripts ? this.setMessage('PayMethodDescripts', 'descripts') : "付款方式："}>
                                                {getFieldDecorator('descripts', {
                                                    initialValue: params && params.descripts ? params.descripts : undefined,
                                                    rules: [{ required: true, message: '请输入付款方式' }],
                                                })(
                                                    <Input></Input>
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={8} style={paddRightCol}>
                                            <FormItem {...formItemLayout} label={this.state.localeProvider && this.state.localeProvider.PayMethodCode ? this.setMessage('PayMethodCode', 'descripts') : "代码："}>
                                                {getFieldDecorator('code', {
                                                    initialValue: params && params.code ? params.code : undefined,
                                                    rules: [{ required: true, message: '请输入代码' }],
                                                })(
                                                    <Input></Input>
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={8} style={paddRightCol}>
                                            <FormItem {...formItemLayout} label={this.state.localeProvider && this.state.localeProvider.PayMethodENDesc ? this.setMessage('PayMethodENDesc', 'descripts') : "英文描述："}>
                                                {getFieldDecorator('eNDesc', {
                                                    initialValue: params && params.eNDesc ? params.eNDesc : undefined,
                                                    rules: [{ required: false, message: '' }],
                                                })(
                                                    <Input></Input>
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={8} style={paddRightCol}>
                                            <FormItem label={this.state.localeProvider && this.state.localeProvider.PayMethodEffectiveDate ? this.setMessage('PayMethodEffectiveDate', 'descripts') : "生效日期："} {...formItemLayout}>
                                                {getFieldDecorator('startDate', {
                                                    initialValue: params && params.startDate ? moment(params.startDate, "YYYY-MM-DD") : moment(),
                                                    rules: [{ required: true, message: '请选择生效日期' }],
                                                })(
                                                    <DatePicker style={{ width: '100%' }} disabledDate={(curDate) => {
                                                        return curDate && curDate > moment().endOf('day');
                                                    }} />
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={8} style={paddRightCol}>
                                            <FormItem label={this.state.localeProvider && this.state.localeProvider.PayMethodExpirationDate ? this.setMessage('PayMethodExpirationDate', 'descripts') : "失效日期："} {...formItemLayout}>
                                                {getFieldDecorator('stopDate', {
                                                    initialValue: params && params.stopDate ? moment(params.stopDate, "YYYY-MM-DD") : undefined,
                                                })(
                                                    <DatePicker style={{ width: '100%' }} />
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={8} style={paddRightCol}>
                                            <FormItem label={this.state.localeProvider && this.state.localeProvider.PayMethodSerialNumber ? this.setMessage('PayMethodSerialNumber', 'descripts') : "序号："} {...formItemLayout}>
                                                {getFieldDecorator('seqNo', {
                                                    initialValue: params && params.seqNo ? params.seqNo : undefined,
                                                    rules: [{ required: false, message: '' }],
                                                })(
                                                    <Input></Input>
                                                )}
                                            </FormItem>
                                        </Col>
                                    </Row>
                                </Form>
                                <DecoctingOrderModal OnChildrefs={this.OnChildrefs} ></DecoctingOrderModal>
                            </div>
                        </Modal>
                    </div>
                </div>
            );
        }
    })
export default ExpressPayment;