/*
 * Creator:     HLH
 * CreatDate:   2019-1-15
 * descripts：  治疗项目评估添加/编辑
 * */
import React from 'react';
import { Form, Input, Select, Button, message, Row, Icon, Divider, Popconfirm, DatePicker, Table, Col,Switch } from 'antd';
import { $http } from 'containers/config/https';
import moment from 'moment';
import store from 'store';
//import DecoctingOrderModal from "../../orderdiatemplet/component/DecoctingOrderModal"
import DecoctingOrderModal from '../../orderdiatemplet/component/DecoctingOrderModal';
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 formLayoutItem = {
    labelCol: { span: 4 },
    wrapperCol: { span: 20 },
}
class CureItemEvaluationDetails extends React.Component {
    constructor() {
        super();
        this.state = {
            info: {},
            size: "small",
            search: "",
            page: 1,
            fieldDesc: undefined,
            fieldArr: [], // 字段下拉框数据
            pageSize: 10,
            cureItemID: "",
            required:false,
            btnStatus: true,

        };
    }
    componentDidMount() {
        this.props.onAttRef(this);
        this.getFieldSelect();
        this.getMainTableColumns();
        document.querySelector(".department-header .ant-table-body").style.height = store.getState().tableHeight.y - 68 + 'px';
        document.querySelector(".department-header .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,
                    })
                }
            }
        })
    }
    //切换
    restCheck=()=>{
        this.setState({
            btnStatus:true,
            selectedRowKeys_right:[],
        })
    }
    //清空数据
    initDeatail = () => {
        this.setState({
            rowIds: "",
            cureItemID: "",
            info: {},
            tableData: [],
            total: 0,
            page: 1,
            required:false,
        })
    }
    clearInfo = () => {
        this.props.form.resetFields();
        this.setState({
            params: {},
            rowIds: "",
            required:false,
            btnStatus:true,
            selectedRowKeys_right:[]
        })
    }
     //上移
     moveUp = () => {
        var keys = this.state.selectedRowKeys_right
        var data = this.state.tableData
        var newKeys = []
        keys = keys.sort(function (m, n) {
          if (m < n) return -1
          else if (m > n) return 1
          else return 0
        });
        for (var i = 0; i < keys.length; i++) {
          if (keys[i] === 0) {
            newKeys.push(keys[i])
            message.warn('已经到顶了，无法再移动！')
            return
          }
          var curRowData = data[keys[i]]
          var curRowKey = curRowData.key
          var upRowData = data[keys[i] - 1]
          var upRowKey = upRowData.key
          upRowData.key = curRowKey
          curRowData.key = upRowKey
          data[keys[i]] = upRowData
          data[keys[i] - 1] = curRowData
          newKeys.push(keys[i] - 1)
        }
        this.setState(
          {
            tableData: data,
            selectedRowKeys_right: newKeys
          }
        )
      }
      //下移
      moveDown = () => {
        var keys = this.state.selectedRowKeys_right
        var data = this.state.tableData
        var newKeys = []
        keys = keys.sort(function (m, n) {
          if (m < n) return -1
          else if (m > n) return 1
          else return 0
        });
        for (var i = keys.length - 1; i >= 0; i--) {
          if (keys[i] === data.length - 1) {
            newKeys.push(keys[i])
            message.warn('已经到底了，无法再移动！')
            return
          }
          var curRowData = data[keys[i]]
          var upRowData = data[keys[i] + 1]
          var curRowKey = curRowData.key
          var upRowKey = upRowData.key
          upRowData.key = curRowKey
          curRowData.key = upRowKey
          data[keys[i]] = upRowData
          data[keys[i] + 1] = curRowData
          newKeys.push(keys[i] + 1)
        }
        this.setState(
          {
            tableData: data,
            selectedRowKeys_right: newKeys
          }
        )
      }
    handleSave = () => {
        const { params, ICD, diaID, info,required,tableData} = this.state
       //排序 
        if(!this.state.btnStatus){
            let arr = this.state.tableData
            arr&&arr.map((item,i)=>{
                item.seqNo = i+1,
                item.updateUserID=sessionStorage.userData ? JSON.parse(sessionStorage.userData).userID : ""
            })
            let newArr = {
                params: arr
            }
            $http.post('urlS', this, {
                code: '01040181',
                data: newArr,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        message.success("排序成功")
                        this.setState({
                            selectedRowKeys_right: [],
                            btnStatus: true,
                            disAdd: false,
                            canSaveStatus: true
                          })
                    }
                }
            })
            
        }else{
        //保存修改
        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()
                                })

                            }
                            this.setState({
                                selectedRowKeys_right: [],
                                btnStatus: true,
                                disAdd: false,
                                canSaveStatus: true
                              })
                        }
                    }
                })

            }
        })
        }
     
    }
    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.setState({
                        selectedRowKeys_right: [],
                        btnStatus: true,
                        canSaveStatus: true,
                        disAdd: false,
                        // ordShow:false,
                      })
                    this.clearInfo()
                }
            }
        })
    }
    //动态表头
    onColumnRef = (ref) => {
        this.columnRef = ref;
    }
    // 获取主列表columns
    getMainTableColumns = () => {
        let data = {
            params: [{
                compontName: "CureItemEvaluation",
                reactCode: ['CureItemEvaluation'],
                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: "50px",
                        code: "edit",
                        dataIndex: "edit",
                        title: "操作",
                        display: "Y",
                        render: (value, row, index) => {
                            return (
                                <span>
                                    <Popconfirm title="是否要删除此行" onConfirm={() => this.del(row)}>
                                        <Button disabled={!this.state.btnStatus} style={{color:!this.state.btnStatus?"rgba(0, 0, 0, 0.25)":"#fd0101a6",border:"0"}}>删除</Button>
                                    </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} 条`;
    }
    restAll=()=>{
        this.setState({
            rowIds: "",
            params: {},
            required:false,
            btnStatus: true,
            selectedRowKeys_right:[]
        });
        this.props.form.resetFields()
    }
    //点击Row
    onClickRow = (record) => {
        return {
            onClick: () => {
                if(!this.state.btnStatus){
                    return
                }
                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,
                        btnStatus: true,
                    })
                } 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.restAll()

                    }
                }
            },
        };
    }
    //点击查询后 表格行
    setRowClassNames = (record) => {
        return record.ID === this.state.rowIds ? 'clickRowStyle' : '';
    }
    handleSwithChange=(v)=>{
        this.setState({
            required:v
        })
    }
    render() {
        const { getFieldDecorator } = this.props.form;
        const { params, columns, fieldArr,required } = this.state

        let fieldOp = []
        fieldArr && fieldArr.map((item) => {
            fieldOp.push(<Option key={item.id} value={String(item.id)}>{item.descripts}</Option>)
        })

        const rowSelection_right = {
            selectedRowKeys: this.state.selectedRowKeys_right,
            onChange: (selectedRowKeys, selectedRows) => {
              this.clearInfo()
              let btnStatus = false;
              let canSaveStatus = false;
              let selectrow = "";
              if (selectedRowKeys.length === 0) {
                btnStatus = true;
                canSaveStatus = true;
              } else {
                selectrow = selectedRowKeys[selectedRowKeys.length - 1];
              }
              this.setState({ btnStatus: btnStatus, canSaveStatus: canSaveStatus, selectrow: selectrow, selectedRow_right: selectedRows, selectedRowKeys_right: selectedRowKeys });
            },
            onSelectAll: (selected, selectedRows, changeRows) => {
                this.clearInfo()
              if (selectedRows.length > 0) {
                this.setState({
                  btnStatus: false,
                  canSaveStatus: false,
                })
              } else {
                this.setState({
                  btnStatus: true,
                  canSaveStatus: true,
                })
              }
              this.setState({ selectedRow_right: selectedRows });
            }
          };
        return (
            <div className="department-header">
                <Form>
                    <Row gutter={60} style={{ margin: '0' }}>
                        <Col span={6} style={paddRightCol}>
                            <FormItem label='字段' {...formItemLayout}>
                                {getFieldDecorator('fieldID', {
                                    initialValue: params && params && params.fieldID ? params.fieldID : undefined,
                                    rules: [{ required: true, message: '' }],
                                })(
                                    <Select
                                        placeholder=""
                                        onChange={this.handleSelectChange}
                                        onSelect={this.handleStatus}
                                        disabled={!this.state.btnStatus}
                                    >
                                        {fieldOp}
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={6} style={paddRightCol}>
                            <FormItem label='默认值' {...formItemLayout}>
                                {getFieldDecorator('defaultValue', {
                                    initialValue: params && params && params.defaultValue ? params.defaultValue : undefined,
                                    rules: [{ required: false, message: '' }],
                                })(
                                    <Input allowClear disabled={!this.state.btnStatus}/>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={6} style={paddRightCol}>
                            <FormItem label='必填' {...formItemLayout}>
                                {getFieldDecorator('required', {
                                    initialValue:undefined,
                                    rules: [{ required: false, message: '' }],
                                })(
                                    <Switch disabled={!this.state.btnStatus} checkedChildren={this.state.localeProvider && this.state.localeProvider.BlacklistInformationInterfacYes ? this.setMessage('BlacklistInformationInterfacYes', 'descripts') : '是'} unCheckedChildren={this.state.localeProvider && this.state.localeProvider.BlacklistInformationInterfacNo ? this.setMessage('BlacklistInformationInterfacNo', 'descripts') : '否'} checked={required}  onChange={(val) => this.handleSwithChange(val,)} />

                                )}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={6} style={paddRightCol}>
                            <FormItem label='生效日期' {...formItemLayout}>
                                {getFieldDecorator('startDate', {
                                    initialValue: params && params.startDate ? moment(params.startDate, "YYYY-MM-DD") : moment(),
                                    rules: [{ required: true, message: '请选择生效日期' }],
                                })(
                                    <DatePicker disabled={!this.state.btnStatus} style={{ width: '100%' }} disabledDate={(curDate) => {
                                        return curDate && curDate > moment().endOf('day');
                                    }} />
                                )}
                            </FormItem>
                        </Col>
                        <Col span={6} style={paddRightCol}>
                            <FormItem label='失效日期' {...formItemLayout}>
                                {getFieldDecorator('stopDate', {
                                    initialValue: params && params.stopDate ? moment(params.StopDated, "YYYY-MM-DD") : undefined,
                                    rules: [{ required: false, message: '' }],
                                })(
                                    <DatePicker disabled={!this.state.btnStatus} style={{ width: '100%' }} />
                                )}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row gutter={60} style={{ margin: '0' }}>
                        <Col span={24} style={{ textAlign: "right", paddingRight: "0", margin: "-8px 0 8px 0" }}>
                        <Button disabled={this.state.btnStatus} size="small" type="dashed" onClick={this.moveUp} style={{ marginRight: '10px' }}><Icon type="up-circle" />上移</Button>
                        <Button disabled={this.state.btnStatus} size="small" type="dashed" onClick={this.moveDown} style={{ marginRight: '10px' }}><Icon type="down-circle" />下移</Button>
                            <Button key="submitc" type="primary" disabled={this.state.cureItemID == ""||!this.state.btnStatus} onClick={this.clearInfo} style={{ margin: "0 8px" }}>清空</Button>
                            <Button key="submits" type="primary" disabled={this.state.cureItemID == ""} onClick={this.handleSave}>保存</Button>
                        </Col>
                    </Row>
                </Form>
                <DecoctingOrderModal OnChildrefs={this.OnChildrefs} handleParms={this.handleParms}></DecoctingOrderModal>
                <Table
                    columns={columns}
                    dataSource={this.state.tableData}
                    pagination={false}
                    rowKey={record => record.key}
                    onRow={this.onClickRow}
                    rowClassName={this.setRowClassNames}
                    rowSelection={rowSelection_right}
                    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='CureItemEvaluation'
                    configType="C"
                    onRef={this.onColumnRef}
                    reloadData={this.getMainTableColumns}
                />
            </div>
        )
    }
};
const CureItemEvaluationDetail = Form.create()(CureItemEvaluationDetails);
export default CureItemEvaluationDetail;
