///全局配置
import React from 'react';
import { Select, Input, Row, Col, Button, Spin, Divider, Popconfirm, message, Icon, Form, Modal, Card, Switch, DatePicker, Popover, List, Tooltip, InputNumber } from 'antd';
import { $http } from '../../containers/config/https';
import '../../assets/css/system.css';
import PubilcTablePagination from '../common/PubilcTablePagination.jsx';
import store from './../../store/index';
import moment from 'moment';

const { Option } = Select;
const FormItem = Form.Item;

const formItemLayout = {
  labelCol: { span: 10 },
  wrapperCol: { span: 14 },
}

const formItemLayoutNumber = {
  labelCol: { span: 9 },
  wrapperCol: { span: 14 },
}

const HospitalMaintenance = Form.create()(
  class HospitalMaintenance extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        data: [],
        columns: [],
        total: 0,
        page: 1,
        pageSize: 10,
        baseParms: {},
        values: {},
        id: "",

        cityArr: [],
        areasArr: [],
        VillagesArr: [],
        hamletsArr: [],

        heightTable: "",
      }
    }
    componentDidMount() {
      // 初始化设置table的高度以及表体的高度 内容高度 height 
      if (document.querySelector('.ant-table-body')) {
        document.querySelector('.ant-table-body').style.height = store.getState().tableHeight.y - 40 + 'px'
      }
      this.getBaseParams();
    }
    //获取对应的医院基础信息数据
    getBaseParams = () => {
      let data = {
        params: [{
          //hospID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).hospID : ''
        }],
      }
      $http.post("urlS", this, {
        code: "03030026",
        data: data,
        success: function (res) {
          if (+res.errorCode === 0) {
            this.setState({
              baseParms: { ...this.state.baseParms, ...{ hosp: res.result.Data } }
            })
          } else {
            message.error('失败：' + res.errorMessage);
          }
        },
        error: function (error) {
          message.error('失败：' + error);
        }
      });
    }
    FindData = () => {
      const { propMethod: { findData } } = this.props;
      this.showModal(false);
      findData();
      this.reset();
    }
    // 页码改变的回调，参数是改变后的页码及每页条数
    PageChange = (page, pageSize) => {
      this.setState({ page: page, pageSize: pageSize }, () => {
        // 重新调用查询方法
        this.FindData()
      });
    }
    // 条数改变的回调
    onShowSizeChange = (current, size) => {
      this.setState({ page: current, pageSize: size }, () => {
        // 重新调用查询方法
        this.FindData()
      });
    }
    save = () => {
      this.props.form.validateFields((err, values) => {
        //const { page, pageSize } = this.state;
        const { data: params } = this.props;
        if (err) return;
        let par = {
          hospID: values.hospID || "",
          productIP: values.productIP || "",
          queryIP: values.queryIP || "",
          overtime: values.overtime || "",
          pWInvalidDays: values.pWInvalidDays || "",
          pWMinLength: values.pWMinLength || "",
          pWComplexity: values.pWComplexity || "",
          pWErrorTimes: values.pWErrorTimes || "",
          accPWErrorTimes: values.accPWErrorTimes || "",
          virtualPath: values.virtualPath || "",
          templatePath: values.templatePath || "",
          CALoginFlag: values.CALoginFlag,
          singleOnline: values.singleOnline,
          patNoLength: values.patNoLength || '',
          EMRIP: values.EMRIP || '',
          EMRPath: values.EMRPath || '',
        };

        if (params && params.id) {
          par = { ...par, ...{ id: params.id } };
        } else {
          //par = { ...par, ...{ hospId: hospID } };
        }

        $http.post("urlS", this, {
          code: "4035",
          data: {
            params: [par]
          },
          success: function (res) {
            if (+res.errorCode === 0) {
              message.success(res.errorMessage)
              this.FindData();
            } else {
              message.error('失败：' + res.errorMessage);
            }
          },
          error: function (error) {
            message.error('失败：' + error);
          }
        });
      })
    }
    // delete = () => {
    //     let data = {
    //         params: [{
    //             hospID: this.state.hospID,
    //             updateUserID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).userID : "",
    //         }],
    //     }
    //     $http.post("urlS", this, {
    //         code: "05100210",
    //         data: data,
    //         success: function (res) {
    //             if (+res.errorCode === 0) {
    //                 message.success("删除成功")
    //                 this.reset()
    //                 this.FindData()
    //             } else {
    //                 message.error('失败：' + res.errorMessage);
    //             }
    //         },
    //         error: function (error) {
    //             message.error('失败：' + error);
    //         }
    //     })
    // }
    reset = () => {
      this.props.form.resetFields();
    }

    // 显示分页总条数
    showTotal(total) {
      return `共 ${total} 条`;
    }
    showModal = (bool) => {
      const { propMethod: { showModal } } = this.props;
      showModal(bool);
      this.reset();
    }
    // getSelectData = (data) => {
    //   if (data) {
    //     if (data.countryId) {
    //       this.getProvince(data.countryId);
    //     }
    //     if (data.provinceId) {
    //       this.getCity(data.provinceId);
    //     }
    //     if (data.cityId) {
    //       this.getAreas(data.cityId);
    //     }
    //     if (data.areaId) {
    //       this.getVillages(data.areaId);
    //     }
    //     if (data.villageId) {
    //       this.getHamlet(data.villageId);
    //     }
    //   }
    // }
    render() {
      const { modalVisible, data: params, propMethod } = this.props;
      const { getFieldDecorator } = this.props.form;
      const { baseParms, provinceArr, cityArr, areasArr, VillagesArr, hamletsArr } = this.state;

      // 医院
      let hospOp = []
      baseParms.hosp && baseParms.hosp.map(item => {
        hospOp.push(<Option key={item.id} role={item.descripts + '^' + item.descriptsSPCode} title={item.descripts} value={String(item.id)}>{item.descripts}</Option>)
      })

      return (
        <Modal
          onCancel={() => this.showModal(false)}
          title={<span>{params ? params.healthBurDesc : ''}</span>}
          visible={modalVisible} width={1200}
          footer={
            <div style={{ display: "flex", justifyContent: "flex-end" }}>
              <Button style={{ marginRight: '30px' }} onClick={() => this.showModal(false)}>取消</Button>
              <Button style={{ marginRight: '30px' }} type="primary" onClick={this.save}>{params && params.id ? "更新" : "新增"}</Button>
              <Button type="primary" onClick={this.reset}>重置</Button>
            </div>
          }
        >
          <Form style={{ height: "100%", overflow: "hidden auto" }}>
            <Row>
              <Col span={6} className="patNameDom">
                <FormItem {...formItemLayout} label='医院'>
                  {getFieldDecorator('hospID', {
                    initialValue: params && params.hospID ? String(params.hospID) : undefined,
                    rules: [{ required: true, message: '请选择医院', },
                    ],
                  })(
                    <Select showSearch allowClear optionFilterProp="role" >
                      {hospOp}
                    </Select>
                  )}
                </FormItem>
              </Col>
              <Col span={6}>
                <FormItem {...formItemLayout} label='生产库ip'>
                  {
                    <Tooltip title={'生产库ip 有负载均衡是负载均衡ip,没有负载均衡ecp 的ip'} >
                      {
                        getFieldDecorator('productIP', {
                          initialValue: params && params.productIP ? params.productIP : undefined,
                          rules: [{ required: true, message: '请输入生产库ip' }],
                        })(

                          <Input />

                        )}
                    </Tooltip>
                  }
                </FormItem>
              </Col>
              <Col span={6}>
                <FormItem {...formItemLayout} label='查询库ip'>
                  {getFieldDecorator('queryIP', {
                    initialValue: params && params.queryIP ? params.queryIP : undefined,
                    rules: [{ required: true, message: '请输入卫生局描述' }],
                  })(
                    <Input />
                  )}
                </FormItem>
              </Col>
              <Col span={6} >
                <FormItem {...formItemLayout} label='超时时间'>
                  {
                    <Tooltip title={'单位：分钟'} >
                      {
                        getFieldDecorator('overtime', {
                          initialValue: params && params.overtime ? params.overtime : undefined,
                          rules: [{ required: true, message: '请输入超时时间' }],
                        })(
                          <InputNumber />
                        )
                      }
                    </Tooltip>
                  }
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span={6} className="patNameDom">
                <FormItem {...formItemLayout} label='密码失效天数'>
                  {
                    <Tooltip title={'单位：天'} >
                      {
                        getFieldDecorator('pWInvalidDays', {
                          initialValue: params && params.pWInvalidDays ? params.pWInvalidDays : undefined,
                          rules: [{ required: true, message: '请输入组织机构代码', },
                          ],
                        })(
                          <InputNumber />
                        )
                      }
                    </Tooltip>
                  }
                </FormItem>
              </Col>
              <Col span={6} className="patNameDom">
                <FormItem {...formItemLayout} label='密码最小长度'>
                  {getFieldDecorator('pWMinLength', {
                    initialValue: params && params.pWMinLength ? params.pWMinLength : undefined,
                    rules: [{ required: true, message: '请输入密码最小长度', },
                    ],
                  })(
                    <InputNumber />
                  )}
                </FormItem>
              </Col>
              <Col span={6} className="patNameDom">
                <FormItem {...formItemLayout} label='用户密码复杂度'>
                  {
                    <Tooltip title={'字母+数字+符号；复杂度1、2、3。  1表示单纯的字母或数字,2表示字母+数字,3表示字母+数字+符号'} >
                      {
                        getFieldDecorator('pWComplexity', {
                          initialValue: params && params.pWComplexity ? params.pWComplexity : undefined,
                          rules: [{ required: true, message: '请输入用户密码复杂度', },
                          ],
                        })(
                          <Input />
                        )
                      }
                    </Tooltip>
                  }
                </FormItem>
              </Col>
              <Col span={6} className="patNameDom">
                <FormItem {...formItemLayout} label='用户密码错误次数'>
                  {getFieldDecorator('pWErrorTimes', {
                    initialValue: params && params.pWErrorTimes ? params.pWErrorTimes : undefined,
                    rules: [{ required: true, message: '请输入用户密码错误次数', },
                    ],
                  })(
                    <InputNumber />
                  )}
                </FormItem>
              </Col>
              <Col span={6} className="patNameDom">
                <FormItem {...formItemLayout} label='帐户密码错误次数'>
                  {getFieldDecorator('accPWErrorTimes', {
                    initialValue: params && params.accPWErrorTimes ? params.accPWErrorTimes : undefined,
                    rules: [{ required: true, message: '请输入帐户密码错误次数', },
                    ],
                  })(
                    <InputNumber />
                  )}
                </FormItem>
              </Col>
              <Col span={6} className="patNameDom">
                <FormItem {...formItemLayout} label='虚拟路径'>
                  {getFieldDecorator('virtualPath', {
                    initialValue: params && params.virtualPath ? params.virtualPath : undefined,
                    rules: [{ required: true, message: '请输入虚拟路径', },
                    ],
                  })(
                    <Input />
                  )}
                </FormItem>
              </Col>
              <Col span={6} className="patNameDom">
                <FormItem {...formItemLayout} label='模板地址'>
                  {getFieldDecorator('templatePath', {
                    initialValue: params && params.templatePath ? params.templatePath : undefined,
                    rules: [{ required: true, message: '请输入模板地址', },
                    ],
                  })(
                    <Input />
                  )}
                </FormItem>
              </Col>
              <Col span={6} className="patNameDom">
                <FormItem {...formItemLayout} label='是否启用ca登录'>
                  {
                    getFieldDecorator('CALoginFlag', {
                      valuePropName: 'checked',
                      initialValue: params && params.CALoginFlag === 'Y' ? true : false,
                      rules: [{ required: false, message: '', },
                      ],
                    })(
                      <Switch />
                    )
                  }
                </FormItem>
              </Col>
              <Col span={6} className="patNameDom">
                <FormItem {...formItemLayout} label='是否启用单一在线'>
                  {
                    getFieldDecorator('singleOnline', {
                      valuePropName: 'checked',
                      initialValue: params && params.singleOnline === 'Y' ? true : false,
                      rules: [{ required: false, message: '', },
                      ],
                    })(
                      <Switch />
                    )
                  }
                </FormItem>
              </Col>
              <Col span={6} className="patNameDom">
                <FormItem {...formItemLayout} label='登记号长度'>
                  {getFieldDecorator('patNoLength', {
                    initialValue: params && params.patNoLength ? params.patNoLength : undefined,
                    rules: [{ required: false, message: '', },
                    ],
                  })(
                    <InputNumber />
                  )}
                </FormItem>
              </Col>
              <Col span={6} className="patNameDom">
                <FormItem {...formItemLayout} label='电子病历服务器路径'>
                  {getFieldDecorator('EMRIP', {
                    initialValue: params && params.EMRIP ? params.EMRIP : undefined,
                    rules: [{ required: false, message: '', },
                    ],
                  })(
                    <Input />
                  )}
                </FormItem>
              </Col>
              <Col span={6} className="patNameDom">
                <FormItem {...formItemLayout} label='电子病历模板路径'>
                  {getFieldDecorator('EMRPath', {
                    initialValue: params && params.EMRPath ? params.EMRPath : undefined,
                    rules: [{ required: false, message: '', },
                    ],
                  })(
                    <Input />
                  )}
                </FormItem>
              </Col>
            </Row>
          </Form>
        </Modal>
      );
    }
  });

class RoleMaintenance extends React.Component {
  constructor() {
    super();
    this.state = {
      // 角色名称
      name: undefined,
      // 关联岗位
      quarters: undefined,
      // 记录状态
      status: undefined,
      // 表格数据
      tableData: [],
      // 表格数据总条数
      total: 0,
      showLoading: true,
      page: 1,
      pageSize: 10,
      selectData: {}, // 下拉框数据
      headerHeight: 0,

      modalVisible: false,
      editData: {}
    };
    this.columns = [
      {
        key: 1,
        title: '医院',
        dataIndex: 'hospDesc',
        align: "center",
        width: '5%'
      },
      {
        key: 2,
        title: '生产库ip',
        dataIndex: 'productIP',
        align: "center",
        width: '5%'
      },
      {
        key: 3,
        title: '查询库ip',
        dataIndex: 'queryIP',
        align: "center",
        width: '5%'
      },
      {
        key: 5,
        title: '超时时间',
        dataIndex: 'overtime',
        align: "center",
        width: '5%'
      },
      {
        key: 6,
        title: '密码失效天数',
        dataIndex: 'pWInvalidDays',
        align: "center",
        width: '5%'
      },
      {
        key: 7,
        title: '密码最小长度',
        dataIndex: 'pWMinLength',
        align: "center",
        width: '5%'
      },
      {
        key: 8,
        title: '用户密码复杂度',
        dataIndex: 'pWComplexity',
        align: "center",
        width: '5%'
      },
      {
        key: 9,
        title: '用户密码错误次数',
        dataIndex: 'pWErrorTimes',
        align: "center",
        width: '5%'
      },
      {
        key: 10,
        title: '帐户密码错误次数',
        dataIndex: 'accPWErrorTimes',
        align: "center",
        width: '5%'
      },
      {
        key: 11,
        title: '虚拟路径',
        dataIndex: 'virtualPath',
        align: "center",
        width: '5%'
      },
      {
        key: 12,
        title: '模板地址',
        dataIndex: 'templatePath',
        align: "center",
        width: '5%'
      },
      {
        key: 13,
        title: '是否启用ca登录',
        dataIndex: 'CALoginFlag',
        align: "center",
        width: '5%'
      },
      {
        key: 14,
        title: '是否启用单一在线',
        dataIndex: 'singleOnline',
        align: "center",
        width: '5%'
      },
      {
        key: 15,
        title: '登记号长度',
        dataIndex: 'patNoLength',
        align: "center",
        width: '5%'
      },
      {
        key: 16,
        title: '电子病历服务器路径',
        dataIndex: 'EMRIP',
        align: "center",
        width: '10%'
      },
      {
        key: 17,
        title: '电子病历模板路径',
        dataIndex: 'EMRPath',
        align: "center"
      },
      {
        title: '操作',
        key: 100,
        align: "center",
        width: 130,
        fixed: 'right',
        render: (text, record) => (
          <span>
            <Icon type="edit" style={{ color: '#108EE9' }}></Icon>
            <span className='span' onClick={() => this.handleCompile(record)}>编辑</span>
            {/* <Divider type="vertical" />
            <Icon type="delete" style={{ color: 'rgba(240,65,52,1)' }}></Icon>
            <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={() => this.handleDetele(record)} >
              <span className='span' style={{ color: 'rgba(240,65,52,1)' }}>删除</span>
            </Popconfirm> */}
          </span>
        ),
      }
    ]
  }

  componentDidMount() {
    // 初始化列表数据
    this.handleQuery();
    // 组件加载完毕关闭loading
    this.setState({ showLoading: false });
  }

  componentWillUnmount() {
    // 组件销毁前将静止让setState修改state的状态
    this.setState = (state, callback) => { return; }
  }

  // 调用子组件的连接事件
  onRef = (ref) => {
    this.child = ref
  }

  // 提供修改page和pageSize的回调函数
  compilePage(page, pageSize) {
    // 修改page，或者pageSize
    this.setState({ page: page, pageSize: pageSize }, () => {
      // 重新调用查询方法
      let { status, name, quarters } = this.state;
      this.getTableData();
    })
  }

  // 请求列表数据
  getTableData() {
    let { page, pageSize } = this.state;
    let data = {};
    this.props.form.validateFields((error, values) => {
      if (error) {
        return;
      }
      data = {
        params: [{
          // hospCode: values.hospCode ? values.hospCode : '',
          // hospDesc: values.hospDesc ? values.hospDesc : '',
          // hospStatus: values.hospStatus ? values.hospStatus : '',
        }],
        pagination: [{
          pageSize: pageSize,
          currentPage: page,
          sortColumn: "",
          sortOrder: ""
        }]
      };
      $http.post('urlS', this, {
        code: "4034",
        data: data,
        success: function (res) {
          if (+res.errorCode === 0) {
            this.setState({ tableData: res.rows, total: res.total }, () => {
              // 数据加载成功关闭loading
              this.child.handleLoading()
            })
          } else {
            this.setState({ tableData: [], total: 0 }, () => {
              // 数据加载成功关闭loading
              this.child.handleLoading();
            })
          }
        },
        error: function () {
          this.setState({ tableData: [], total: 0 }, () => {
            // 数据加载成功关闭loading
            this.child.handleLoading();
          })
        }
      });
    });

  }

  // 查询
  handleQuery = () => {
    this.setState({ page: 1, pageSize: 10 }, () => {
      this.getTableData();
    })
  }

  // 新增跳转到新增界面
  handleAdd = () => {
    this.setState({ editData: { startDate: moment() } });
    this.showModal(true);
  }
  // handleDetele = (record) => {
  //   let data = {
  //     params: [{
  //       healthBurID: record.healthBurID
  //     }]
  //   }
  //   $http.post('urlADS', this, {
  //     code: '05100243',
  //     data: data,
  //     success: function (res) {
  //       if (+res.errorCode === 0) {
  //         message.success('删除成功');
  //         // 刷新列表数据
  //         this.handleQuery();
  //       }
  //     }
  //   })
  // }
  // 编辑
  handleCompile = (record) => {
    this.setState({ editData: record });
    //this.modalRef.getSelectData(record);
    this.showModal(true);
  }
  //控制模态框显示
  showModal = (bool) => {
    this.setState({ modalVisible: bool });
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    // 组件所需参数
    const param = {
      // 表头配置
      columns: this.columns,
      // 表格数据
      data: this.state.tableData,
      // 数据总条数
      total: this.state.total,
      // 当前页数
      page: this.state.page,
      // 表格的宽度
      x: '200%',
      y: store.getState().tableHeight.y + 81 - this.state.headerHeight,
      height: store.getState().tableHeight.y + 50 - this.state.headerHeight + 'px',
    }
    return (
      <Spin tip="加载中..." spinning={this.state.showLoading}>
        <div>
          <Form>
            <Row style={{ margin: '23px 0 0 0' }}>
              <Col span={1} >
              </Col>
              <Col span={2}>
                <Button onClick={this.handleQuery} style={{ margin: '4px 15px 20px 0', background: 'rgba(255,255,255,1)' }}>查询</Button>
              </Col>
              <Col span={2}>
                <Button icon="plus" onClick={this.handleAdd} style={{ background: 'rgba(247,128,93,1)', color: '#fff', margin: '4px 0 0 0' }}>新增配置</Button>
              </Col>
            </Row>
          </Form>
        </div>
        <div style={{ width: '100%', height: '10px', background: '#f0f2f5' }}></div>
        <div style={{ padding: '24px 0 0 0' }} className="table-body-height">
          {/* handelThis将夫组件的属性与方法给子组件访问 */}
          <PubilcTablePagination param={param} handelThis={this} onRef={this.onRef} />
        </div>
        <HospitalMaintenance wrappedComponentRef={(el) => this.modalRef = el} data={this.state.editData} modalVisible={this.state.modalVisible} propMethod={{ showModal: this.showModal, findData: this.handleQuery }} />
      </Spin>
    )
  }
}
export default Form.create()(RoleMaintenance);