/*
 * Creator:     ML
 * CreatDate:   2020-06-09
 * descripts：  上传文件(操作说明书)
*/
import React from 'react';
import { Form, Input, Select, Button, message, Switch, Row, Icon, Divider, Popconfirm, DatePicker, Table, Col, Card, Modal } from 'antd';
import { $http } from 'containers/config/https';
import moment from 'moment';
import store from 'store';
import CommonPagination from 'components/pagination';
import UploadList from './common/UploadList';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import './css/index.less';
const FormItem = Form.Item;
const Option = Select.Option;
const paddRightCol = {
    paddingRight: "0px"
}
const formItemLayout915 = {
    labelCol: { span: 9 },
    wrapperCol: { span: 15 }
}
const formItemLayout = { // label 和input宽度
    labelCol: { span: 6 },
    wrapperCol: { span: 18 },
}

const formItemLayout618 = {
    labelCol: { span: 6 },
    wrapperCol: { span: 18 }
}
class UploadInstruction extends React.Component {
    constructor() {
        super();
        this.state = {
            tableData: [], // 列表数据
            total: 0,
            page: 1,
            pageSize: 10,
            size: "big",
            search: "",
            ICD: "",
            diaID: "",
            size: "small",
            search: "",
            rowIds: "",
            columns: [],
            mechanismArr: [],
            params: {},
            edit: "0",
            visible: false
        };
    }
    componentDidMount() {
        document.querySelector('.ant-table-body').style.height = store.getState().tableHeight.y + 60 + 'px';
        if (this.state.size == "small") {
            this.setState({
                pageSize: 10
            })
        } else {
            this.setState({
                pageSize: 50
            })
        }
        this.getFindDate()
        this.getMainTableColumns()
        this.getMechanism()
    }
    componentWillReceiveProps(nextProps) {
    } //动态表头
    onColumnRef = (ref) => {
        this.columnRef = ref;
    }
    // 获取主列表columns
    getMainTableColumns = () => {
        let data = {
            params: [{
                compontName: "FileDirectory",
                reactCode: ['FileDirectory'],
                // FileDirectory
                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,
                        }
                    }) : '';
                    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 onClick={(e, ) => this.handleAdd(e, "1", row)}>编辑</a>
                                    <Divider type="vertical" />
                                    {/* onConfirm={() => this.toggleEditable("3",row)} */}
                                    <Popconfirm title="是否要删除该目录" >
                                        <a style={{ color: "red" }} >删除</a>
                                    </Popconfirm>
                                </span>
                            )

                        },
                    }
                    filterArr.push(seqArr)
                    this.setState({ columns: filterArr, widthTotal: res.totalWidth })
                }
            }
        })
    }
    //调子组件
    onAttRef = (ref) => {
        this.childAtt = ref
    }
    onRef = (ref) => {
        this.onChildRef = ref
    }
    ondiaRef = (ref) => {
        this.onChilddiaRef = ref
    }
    searchICD = (e) => {
        this.onChildRef.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: ""
            })
        }
    }
    searchdiaICD = (e) => {
        this.onChilddiaRef.showModal(e.target.value)
    }
    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({
            })
        } 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 })
        }
    }
    // 点击查询
    handleQuery = () => {
        this.props.form.validateFields((err, values) => {
            if (!err) {
                this.setState({
                    values,
                    rowIds: "",
                }, () => {
                    //详情页面内容清空
                    this.childAtt.initDeatail()
                    this.onShowSizeChange("1", this.state.pageSize)
                })
            }
        })
    }
    //查询
    getFindDate = (values, e) => {
        let { page, pageSize, diaID, ICD } = this.state;
        let data = {
            params: [{
            }],
            pagination: [{
                pageSize: pageSize,
                currentPage: page,
            }]
        }
        $http.post('urlS', this, {
            code: '01040183',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    this.setState({
                        search: e,
                        tableData: res.result.dataArr,
                        total: res.result.TotalCount,
                    })
                }
            }
        })
    }
    // 修改page和pageSize 跳转至---
    onChange = (e) => {
        this.setState({ page: e, pageSize: this.state.pageSize, }, () => {
            // 重新调用查询方法
            let { values } = this.state;
            this.getFindDate(values);
        })
    }
    //下拉选择页数
    onShowSizeChange = (page, pageSize) => {
        this.setState({ page: 1, pageSize: pageSize }, () => {
            // 重新调用查询方法
            let { values } = this.state;
            this.getFindDate(values, "search");
        })
    }
    // 显示分页总条数
    showTotal(total) {
        return `共 ${total} 条`;
    }
    //点击Row
    onClickRow = (record) => {
        return {
            onClick: () => {
                this.setState({
                    parms: record,
                })
                this.childAtt.clearInfo()
                if (this.state.rowIds === "") {
                    this.setState({
                        rowIds: record.ID,
                    })
                    this.childAtt.getInfo(record)
                } else {
                    if (this.state.rowIds !== record.ID) {
                        this.setState({
                            rowIds: record.ID,
                        });
                        this.childAtt.getInfo(record)
                    } else {
                        this.setState({
                            rowIds: "",
                        });
                        this.childAtt.initDeatail()
                    }
                }
            },
        };
    }
    //点击查询后 表格行
    setRowClassNames = (record) => {
        return record.ID === this.state.rowIds ? 'clickRowStyle' : '';
    }
    //获取机构组织下拉框
    getMechanism = () => {
        let data = {
            params: [{
                logonGroupID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).groupID : "",
                logonHospID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).hospID : "",
            }],
        }
        $http.post('urlS', this, {
            code: '01040001',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    this.setState({
                        mechanismArr: res.result
                    })
                }
            }
        })
    }
    //添加目录
    handleAdd = (e, name, row) => {
        console.log("e-----", e, "roe-----", row)
        this.setState({
            visible: true,
            edit: name
        }, () => {
            this.props.form.resetFields();
            if (name == "0") {
                
            }
        })
    }
    handleOk = () => {
        this.props.form.validateFields((err, values) => {
            if (!err) {
                // let checkFlag = ""
                // if (mes&&mes!="init") {
                //     checkFlag = mes
                // }
                // if (this.state.checked == true) {
                //     checkFlag = "Y"
                // } else {
                //     checkFlag = "N"
                // }
                // let data = {}
                //    data = {
                //     params: [{
                //         code: values.subCode,
                //         descripts: values.subDec,
                //         ordCatID: values.majorBigClassID,
                //         ordTypeID: values.majorType,
                //         status: checkFlag,
                //     }],
                //     pagination: [{
                //         pageSize: parseInt(pageSize),
                //         currentPage: parseInt(page),
                //     }]
                // } 
                // $http.post('urlS', this, {
                //     code: '05100227',
                //     data: data,
                //     success: function (res) {
                //         if (+res.errorCode === 0) {
                //             if(mes&&mes=="init"){
                //                 this.props.findSubTable(res.result.Data,res.result.TotalCount,mes)
                //             }else{
                //                 this.props.findSubTable(res.result.Data,res.result.TotalCount,)
                //             }
                //         }
                //     }
                // })
                this.setState({
                    visible: false
                })
            }

        })

    }
    handleCancel = () => {
        this.setState({
            visible: false
        })
    }
    render() {
        const { columns, mechanismArr, params } = this.state;
        const { getFieldDecorator } = this.props.form;
        let mechanismOp = []
        mechanismArr && mechanismArr.map((item) => {
            mechanismOp.push(<Option key={item.id} value={String(item.id)} title={item.descripts} role={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
        })
        return (
            <div className="uploadFile-dom">
                <Row>
                    <Col span={8}>
                        <Card title={
                            <span style={{ display: "flex", alignItems: "center" }}>
                                <span style={{ display: "inline-block", width: "2px", height: "18px", background: "green", marginRight: "4px" }}>
                                </span>目录
                            </span>
                        } className="titleDom">
                            <Row>
                                <Col span={14} style={paddRightCol}>
                                    <FormItem label='所属机构' {...formItemLayout}>
                                        {getFieldDecorator('hospID', {
                                            initialValue: undefined,
                                            rules: [{ required: false, message: '' }],
                                        })(
                                            <Select
                                                style={{ width: "100%" }}
                                                showSearch
                                                optionFilterProp="role"
                                            >
                                                {mechanismOp}
                                            </Select>
                                        )}
                                    </FormItem>
                                </Col>
                                <Col span={10} style={{ textAlign: "right", height: "50px", lineHeight: "40px" }}>
                                    <span style={{ color: "blue", cursor: "pointer" }} onClick={(e, ) => this.handleAdd(e, "0")}>+ 添加目录</span>
                                </Col>
                            </Row>
                            <div style={{ padding: '4px 2px' }} className="file-dom">
                                <Modal
                                    className='file-modal'
                                    width='600px'
                                    visible={this.state.visible}
                                    title={this.state.edit == "1" ? "编辑文件目录" : "添加文件目录"}
                                    onOk={this.handleOk}
                                    onCancel={this.handleCancel}
                                    footer={[
                                        <Button key="submit" type="primary" loading={this.setState.loading} disabled={this.state.rowId == ""} onClick={this.handleOk}>确定</Button>,
                                        <Button key="cancel" type="primary" loading={this.setState.loading} onClick={this.handleCancel}>取消</Button>,
                                    ]}>
                                    <div className="department-header">
                                        <Form>
                                            <Row gutter={60} style={{ margin: '0' }}>
                                                <Col span={8}>
                                                    <FormItem label='序号' {...formItemLayout915}>
                                                        {getFieldDecorator('seqNo', {
                                                            initialValue: params && params.seqNo ? params.seqNo : undefined,
                                                            rules: [{ required: true, message: '请输入序号' }],
                                                        })(
                                                            <Input type="number"></Input>
                                                        )}
                                                    </FormItem>
                                                </Col>
                                                <Col span={16} >
                                                    <FormItem label='目录名称' {...formItemLayout618}>
                                                        {getFieldDecorator('directoryName', {
                                                            initialValue: params && params.directoryName ? params.directoryName : undefined,
                                                            rules: [{ required: true, message: '请输入目录名称' }],
                                                        })(
                                                            <Input />
                                                        )}
                                                    </FormItem>
                                                </Col>
                                                <Col span={16}>
                                                    <FormItem label='上级目录' {...formItemLayout618}>
                                                        {getFieldDecorator('parentDirectory', {
                                                            initialValue: params && params.parentDirectory ? params.parentDirectory : undefined,
                                                            rules: [{ required: true, message: '请选择上级目录' }],
                                                        })(
                                                            <Select
                                                                style={{ width: "100%" }}
                                                                showSearch
                                                                optionFilterProp="role"
                                                            >
                                                                {mechanismOp}
                                                            </Select>
                                                        )}
                                                    </FormItem>
                                                </Col>
                                            </Row>
                                        </Form>
                                    </div>
                                </Modal>
                            </div>
                            <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 + 60 + 'px', overflow: "auto" }}
                            />
                            <CommonPagination size={this.state.size} 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)} />
                        </Card>
                    </Col>
                    <Col span={16} style={{ marginLeft: "-1px" }}>
                        <Card title={
                            <span style={{ display: "flex", alignItems: "center" }}>
                                <span style={{ display: "inline-block", width: "2px", height: "18px", background: "green", marginRight: "4px" }}>
                                </span>文件列表
                            </span>
                        } className="titleDom">
                            <UploadList onAttRef={this.onAttRef} handleQuery={this.handleQuery}></UploadList>
                        </Card>
                    </Col>
                </Row>
                <ColumnAuthoritysModel
                    clientWidth='800px'
                    compontName='FileDirectory'
                    configType="C"
                    onRef={this.onColumnRef}
                    reloadData={this.getMainTableColumns}
                />
            </div>
        )
    }
};
const UploadInstructions = Form.create()(UploadInstruction);
export default UploadInstructions;