/*
 * Creator:     ML
 * CreatDate:   2020-06-09
 * descripts：  上传文件(操作说明书) 文件目录
*/
import React from 'react';
import { Form, Input, Select, Button, message, Row, Icon, Divider, Popconfirm, DatePicker, Table, Col, Switch, Upload, } from 'antd';
import { $http } from 'containers/config/https';
import moment from 'moment';
import store from 'store';
import CommonPagination from 'components/pagination';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
const { Option } = Select;
const paddRightCol = {
    paddingRight: "0px"
}

const FormItem = Form.Item;

const formItemLayout = { // label 和input宽度
    labelCol: { span: 9 },
    wrapperCol: { span: 15 },
}
const formItemLayout519 = {
    labelCol: { span: 5 },
    wrapperCol: { span: 19 },
}
const formLayoutItem = {
    labelCol: { span: 4 },
    wrapperCol: { span: 20 },
}
class UploadLists extends React.Component {
    constructor() {
        super();
        this.state = {
            info: {},
            size: "small",
            search: "",
            page: 1,
            fieldDesc: undefined,
            fieldArr: [], // 字段下拉框数据
            pageSize: 10,
            cureItemID: "",
            required: false,
            fileList: [],
            iconImg: "http://172.18.100.86:3008/uploadFile?fileType=photo",
            filePath: "",
            canUp: true
        };
    }
    componentDidMount() {
        this.props.onAttRef(this);
        this.getFieldSelect();
        this.getMainTableColumns();
        document.querySelector(".uploadList-dom .ant-table-body").style.height = store.getState().tableHeight.y - 68 + 'px';
        document.querySelector(".uploadList-dom .ant-table-body").style.maxHeight = store.getState().tableHeight.y - 68 + 'px';
    }
    onRef = (ref) => {
        this.onChildRef = ref
    }
    ondiaRef = (ref) => {
        this.onChilddiaRef = ref
    }
    searchICD = (e) => {
        this.onChildRef.showModal(e.target.value)
    }
    searchdiaICD = (e) => {
        this.onChilddiaRef.showModal(e.target.value)
    }
    changeICD = (e) => {
        if (e && e.target.value.length == 0) {
            this.setState({
                ICD: ""
            })
        }
    }
    changediaICD = (e) => {
        if (e && e.target.value.length == 0) {
            this.setState({
                diaID: ""
            })
        }
    }
    handleParms = (data) => {
        this.setState({
            ICD: data.id,
        })
        this.props.form.setFieldsValue({ ICDID: data.descripts, })
    }
    handlediaParms = (data) => {
        this.setState({
            diaID: data.id
        })
        this.props.form.setFieldsValue({ diaICDID: data.descripts })
    }
    handleClear = () => {
        if (this.state.ICD && this.state.ICD) {
            this.setState({
                // ICD,
            })
        } else {
            this.setState({ ICD: "" })
            this.props.form.setFieldsValue({ ICDID: undefined })
        }
    }
    handlediaClear = () => {
        if (this.state.diaID && this.state.diaID) {
            this.setState({
                // diaID,
            })
        } else {
            this.setState({ diaID: "" })
            this.props.form.setFieldsValue({ diaICDID: undefined })
        }
    }
    getInfo = (info) => {
        this.clearInfo()
        this.getDetail(info)
        this.setState({
            info,
            //   ICD:info.nationDiaID,
            //   diaID:info.diaID
        })
    }
    //获取详细信息
    getDetail = (info) => {
        // debugger
        const { pageSize, page } = this.state
        this.setState({
            info: info,
            cureItemID: info.ID,
        })
        let data = {
            params: [{
                cureItemID: info.ID
            }],
            pagination: [{
                pageSize: parseInt(pageSize),
                currentPage: parseInt(page),
            }]
        }
        $http.post('urlS', this, {
            code: '01040180',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    this.setState({ tableData: res.result.data, total: res.result.TotalCount })
                }
            }
        })
    }
    //获取字段下拉框
    getFieldSelect = () => {
        let data = {
            params: [{
            }],
        }
        $http.post('urlS', this, {
            code: '01040189',
            data: data,
            success: function (res) {
                if (res.errorCode == 0) {
                    this.setState({
                        fieldArr: res.result.data,
                    })
                }
            }
        })
    }
    //清空数据
    initDeatail = () => {
        this.setState({
            rowIds: "",
            cureItemID: "",
            info: {},
            tableData: [],
            total: 0,
            page: 1,
            required: false
        })
    }
    clearInfo = () => {
        this.props.form.resetFields();
        this.setState({
            params: {},
            rowIds: "",
            required: false
        })
    }
    handleSave = () => {
        const { params, ICD, diaID, info, required } = this.state
        this.props.form.validateFields((err, values) => {
            if (!err) {
                let data = {
                    params: [{
                        ID: params && params.ID ? params.ID : "",
                        cureItemID: this.state.cureItemID ? this.state.cureItemID : "",
                        seqNo: values.seqNo || "",
                        fieldID: values.fieldID ? values.fieldID : "",
                        required: required == true ? "Y" : "N",
                        defaultValue: values.defaultValue || "",
                        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: '01040181',
                    data: data,
                    success: function (res) {
                        if (+res.errorCode === 0) {
                            if (params && params.id) {
                                message.success("更新成功")
                                this.getDetail(info)
                                this.clearInfo()
                            } else {
                                message.success("添加成功")
                                let lastPage = Math.ceil((this.state.total + 1) / this.state.pageSize)
                                this.setState({
                                    page: lastPage,
                                }, () => {
                                    this.getDetail(info)
                                    this.clearInfo()
                                })

                            }
                        }
                    }
                })

            }
        })
    }
    del = (row) => {
        let data = {
            params: [{
                ID: row && row.ID ? row.ID : "",
                updateUserID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).userID : ""
            }],
        }
        $http.post('urlS', this, {
            code: '01040182',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    message.success("删除成功")
                    this.getDetail(this.state.info)
                    this.clearInfo()
                }
            }
        })
    }
    //动态表头
    onColumnRef = (ref) => {
        this.columnRef = ref;
    }
    // 获取主列表columns
    getMainTableColumns = () => {
        let data = {
            params: [{
                compontName: "FileList",
                reactCode: ['FileList'],
                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()}>{item.title}</div>,
                            display: item.display,
                            key: item.seqNo,
                            render: (text, record) => {
                                if (item.code == "required") {
                                    return (
                                        <span>{record.required == "Y" ? "是" : "否"}</span>
                                    )
                                }
                                return text
                            }
                        }
                    }) : '';
                    let filterArr = arr.filter(function (item) { return item.display === 'Y' });
                    let seqArr = {
                        align: "center",
                        widthNum: 140,
                        width: "120px",
                        code: "edit",
                        dataIndex: "edit",
                        title: "操作",
                        display: "Y",
                        render: (value, row, index) => {
                            return (
                                <span>
                                    <a >编辑</a>
                                    <Divider type="vertical" />
                                    <Popconfirm title="是否要删除此行" onConfirm={() => this.del(row)}>
                                        <a style={{ color: "red" }} >删除</a>
                                    </Popconfirm>
                                </span>
                            )
                        },
                    }
                    filterArr.push(seqArr)
                    this.setState({ columns: filterArr, widthTotal: res.totalWidth })
                }
            }
        })
    }
    //子组件 搜索医嘱项
    OnChildrefs = (ref) => {
        this.child = ref
    }
    //接收子组件 医嘱项id 描述
    handleParms = (record) => {
        this.props.form.setFieldsValue({ medItemDr: record.descripts })
        this.setState({
            cureItemID: record.ID
        })
    }

    // 修改page和pageSize 跳转至---
    onChange = (e) => {
        this.setState({ page: e, pageSize: this.state.pageSize, }, () => {
            // 重新调用查询方法
            let { values, info } = this.state;
            this.getDetail(info);
        })
    }
    //下拉选择页数
    onShowSizeChange = (page, pageSize) => {
        this.setState({ page: 1, pageSize: pageSize, search: "search" }, () => {
            // 重新调用查询方法
            let { values, info } = this.state;
            this.getDetail(info);
        })
    }
    // 显示分页总条数
    showTotal(total) {
        return `共 ${total} 条`;
    }
    //点击Row
    onClickRow = (record) => {
        return {
            onClick: () => {
                this.setState({
                    params: record,
                })
                this.props.form.resetFields()
                if (this.state.rowIds === "") {
                    this.setState({
                        rowIds: record.ID,
                        params: record,
                        cureItemID: record.cureItemID,
                        required: record.required == "Y" ? true : false
                    })
                } else {
                    if (this.state.rowIds !== record.ID) {
                        this.setState({
                            rowIds: record.ID,
                            params: record,
                            cureItemID: record.cureItemID,
                            required: record.required == "Y" ? true : false
                        });
                    } else {
                        this.setState({
                            rowIds: "",
                            params: {},
                            required: false
                        });
                        this.props.form.resetFields()
                    }
                }
            },
        };
    }
    //点击查询后 表格行
    setRowClassNames = (record) => {
        return record.ID === this.state.rowIds ? 'clickRowStyle' : '';
    }
    handleSwithChange = (v) => {
        this.setState({
            required: v
        })
    }
    beforeUpload = (file, name) => {
        // console.log("file-00-----", file)
        const isJpgOrPng = file.type === 'text/plain' || file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ||
            file.type === "application/vnd.ms-excel" || file.type === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        if (!isJpgOrPng) {
            message.error('只能上传text/docx/xls/xlsx/文本文件!');
            this.setState({
                canUp: false
            })
        } else {
            this.setState({
                canUp: true
            })
        }
        // const isLt2M = file.size / 1024 / 1024 < 2;
        // if (!isLt2M) {
        //     message.error('图片大小不能超过2MB!');
        // }
        return false;
    }
    getBase64 = (file, callback) => {
        const reader = new FileReader();
        reader.addEventListener('load', () => callback(reader.result));
        reader.readAsDataURL(file);
    }

    onChangeFile = (info, name, flag) => {
        console.log("info", info)
        this.getBase64(info.file, fielUrl =>
            console.log("fielUrl")

        );
        if (this.state.iconImg !== "" && this.state.canUp) {
            if (info.file.status == "removed") {
                let a = this.state.fileList.filter(data => {
                    if (data.status !== "removed") {
                        return data;
                    }
                });
                this.setState({ fileList: a });
            } else {
                let formData = new FormData();
                formData.append("file", info.file);
                const option = {
                    method: 'post',
                    mode: 'cors',
                    headers: {},
                    body: formData
                };

                fetch(this.state.iconImg, option).then(response => {
                    if (response.ok) {
                        return response.text();
                    } else {
                        console.log('网络错误，请稍后再试');
                        return;
                    }
                }).then(data => {
                    let dataS = JSON.parse(data);
                    let str = this.state.iconImg.match(/(\S*)\/uploadFile/)[1];
                    //    console.log("str--",str,"dataS.filePath",dataS.filePath)
                    this.setState({
                        filePath: str + "//" + dataS.filePath
                    })
                    this.props.form.setFieldsValue({
                        filePath: str + "//" + dataS.filePath
                    })

                })

            }
        }
    }
    render() {
        const { getFieldDecorator } = this.props.form;
        const { params, columns, fieldArr, required, fileList } = this.state

        let fieldOp = []
        fieldArr && fieldArr.map((item) => {
            fieldOp.push(<Option key={item.id} value={String(item.id)}>{item.descripts}</Option>)
        })
        return (
            <div className="uploadList-dom">
                <Form>
                    <Row gutter={60} style={{ margin: '0' }}>
                        <Col span={6} style={paddRightCol}>
                            <FormItem label='序号' {...formItemLayout}>
                                {getFieldDecorator('seqNo', {
                                    initialValue: params && params && params.seqNo ? params.seqNo : undefined,
                                    rules: [{ required: true, message: '请输入序号' }],
                                })(
                                    <Input></Input>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={12} style={paddRightCol}>
                            <FormItem label='标题' {...formLayoutItem}>
                                {getFieldDecorator('title', {
                                    initialValue: params && params && params.title ? params.title : undefined,
                                    rules: [{ required: true, message: '请填写标题' }],
                                })(
                                    <Input allowClear />
                                )}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row style={{ position: "relative" }}>
                        <Col span={15} style={paddRightCol}>
                            <FormItem label='文件路径' {...formItemLayout519}>
                                {getFieldDecorator('filePath', {
                                    // initialValue: params && params.route ? params.route : undefined,
                                    // initialValue:this.state.filePath || "请在右侧选择文件",
                                    rules: [{ required: true, message: '请选择文件' }],
                                })(
                                    <Input placeholder="请在右侧选择文件上传" disabled style={{ border: "0", background: "#fff", cursor: "default" }}>
                                    </Input>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={9} style={{ position: "initial", height: "32px", lineHeight: "38px" }}>
                            {
                                this.state.cureItemID == "" ? <Button disabled style={{background:"#fff",border:"0"}}>
                                    请选择文件
                               </Button> : <Upload
                                        accept="file/txt,file/docx"
                                        // listType="picture-card"
                                        fileList={fileList}
                                        beforeUpload={(e) => this.beforeUpload(e, "onePath")}
                                        onChange={(e) => this.onChangeFile(e, "onePath", "oneFlag")} >
                                        <p style={{ color: "blue" ,cursor:"pointer"}}>
                                            请选择文件
                               </p>
                                    </Upload>
                            }
                        </Col>
                    </Row>
                    <Row gutter={60} style={{ margin: '0' }}>
                        <Col span={24} style={{ textAlign: "right", paddingRight: "0", margin: "-8px 0 8px 0" }}>
                            <Button key="submitc" type="primary" disabled={this.state.cureItemID == ""} onClick={this.clearInfo} style={{ margin: "0 8px" }}>清空</Button>
                            <Button key="submits" type="primary" disabled={this.state.cureItemID == ""} onClick={this.handleSave}>保存</Button>
                        </Col>
                    </Row>
                </Form>
                <Table
                    columns={columns}
                    dataSource={this.state.tableData}
                    pagination={false}
                    rowKey={record => record.key}
                    onRow={this.onClickRow}
                    rowClassName={this.setRowClassNames}
                    bordered
                    style={{ height: store.getState().tableHeight.y - 68 + 'px', overflow: "auto" }}
                />
                <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={this.state.tableData}
                    onChange={this.onChange.bind(this)} />
                <ColumnAuthoritysModel
                    clientWidth='800px'
                    compontName='FileList'
                    configType="C"
                    onRef={this.onColumnRef}
                    reloadData={this.getMainTableColumns}
                />
            </div>
        )
    }
};
const UploadList = Form.create()(UploadLists);
export default UploadList;
