import React from 'react';
import { Table, Popconfirm, Icon, message, DatePicker, Switch, Modal, Form, Divider, Select, Row, Col, Button } from 'antd';
import { $http } from '../../containers/config/https';
import moment from 'moment';
import store from '../../store';
import CommonPagination from 'components/pagination/index';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';


const { Option } = Select;
const dateFormat = 'YYYY-MM-DD'; //定义全局日期格式
const formItemLayout = {    // label 和input宽度
  labelCol: { span: 8 },
  wrapperCol: { span: 14, offset: 2 },
};

class OPAdmReaCon extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false, //加载状态标志
      visible: false, //弹窗显示状态标志
      hospital: [], //医院下拉框数据
      admReaConDr: [], //就诊类型下拉框数据
      admReasonDr: [], //病人费别下拉框数据
      Hosp: [], //表单医院下拉框数据
      ReaCon: [], //表单就诊类型下拉框数据
      Reason: [], //表单病人费别下拉框数据
      tableData: [], // 表格数据
      columns: [], //表格列表
      total: 0,  // 表格数据总条数
      page: 1, //当前页数
      pageSize: 10, //每页显示条数
      updateID: '', //修改表单ID
      admReaSonHosp: JSON.parse(window.sessionStorage.userData).hospID, //病人费别下拉框数据医院限制
      selectHosp: JSON.parse(window.sessionStorage.userData).hospID, //医院查询条件
      selectReaCon: '', //就诊类型查询条件
      selectReason: '', //病人费别查询条件
      modalState: '', //弹窗点击提交时判断是否修改或增加标志
      initialHosp: JSON.parse(window.sessionStorage.userData).hospID, //弹窗初始化医院
      initialReaCon: '', //弹窗初始化就诊类型
      initialReason: '', //弹窗初始化病人费别
      initialStartdate: undefined, //弹窗初始化开始日期
      initialStopdate: undefined, //弹窗初始化失效日期
      initialIsdefault: false, //弹窗初始化是否默认
      motalTitle: '', //弹窗标题
      delAdmReaConID: '', //删除ID
      startValue: null, //日期选择器开始时间
      endValue: null, //日期选择器结束时间

      languageTable1: {}, // 国际化Table1
      languageTable2: {}, // 国际化Table2
      languageData: {}, // 国际化语言包
      language: {},   // 国际化语言
      languageCode: JSON.parse(window.sessionStorage.userData).language, // 国际化语言标识

    };
    // this.columns = [
    //   {
    //     title: '医院',
    //     dataIndex: 'HospDesc',
    //     key: 'HospDesc',
    //     width: '160px',
    //     align: "center",
    //   },
    //   {
    //     title: '就诊类型',
    //     dataIndex: 'AdmReaConDrDesc',
    //     key: 'AdmReaConDrDesc',
    //     width: '100px',
    //     align: "center",
    //   },
    //   {
    //     title: '病人费别',
    //     dataIndex: 'AdmReasonDrDesc',
    //     key: 'AdmReasonDrDesc',
    //     width: '100px',
    //     align: "center",
    //   },
    //   {
    //     title: '开始日期',
    //     dataIndex: 'StartDate',
    //     key: 'StartDate',
    //     width: '100px',
    //     align: "center",
    //   },
    //   {
    //     title: '失效日期',
    //     dataIndex: 'StopDate',
    //     key: 'StopDate',
    //     width: '100px',
    //     align: "center",
    //     render: (text, record) => (
    //       <span>
    //         {record.StopDate === '' || !record.StopDate ? '/' : record.StopDate}
    //       </span>
    //     ),
    //   },
    //   {
    //     title: '创建日期',
    //     dataIndex: 'CreateDate',
    //     key: 'CreateDate',
    //     width: '100px',
    //     align: "center",
    //   },
    //   {
    //     title: '创建时间',
    //     dataIndex: 'CreateTime',
    //     key: 'CreateTime',
    //     width: '100px',
    //     align: "center",
    //   },
    //   {
    //     title: '是否默认',
    //     dataIndex: 'IsDefault',
    //     key: 'IsDefault',
    //     width: '60px',
    //     align: "center",
    //   },
    //   {
    //     title: '创建人',
    //     dataIndex: 'CreateUserDesc',
    //     key: 'CreateUserDesc',
    //     width: '100px',
    //     align: "center",
    //   },
    //   {
    //     title: '操作',
    //     key: 'op',
    //     align: "center",
    //     render: (text, record) => (
          // <span>
          //   <span className='span' onClick={() => this.showModal(record)}><Icon type="edit" />修改</span>
          //   <Divider type="vertical" />
          //   <Popconfirm
          //     title="确定要删除吗?"
          //     onConfirm={this.delConfirm}
          //     okText="是"
          //     cancelText="否"
          //   >
          //     <span style={{ color: '#f00' }} className='span' onClick={() => this.setState({ delAdmReaConID: record.id })}><Icon type="delete" />删除</span>
          //   </Popconfirm>
          // </span>
    //     ),
    //   },
    // ];
  }

  //render 自定义项目名称
  listAdd = (i, j, languageCode) => {
    let { columns } = this.state
    columns.splice(i, j,
      {
        title: languageCode === 'CN' ? "操作" : 'Operation',
        key: 'op',
        align: "center",
        render: (text, record) => (
          <span>
            <span className='span' onClick={() => this.showModal(record)}><Icon type="edit" />{languageCode === 'CN' ? "修改" : 'Alter'}</span>
            <Divider type="vertical" />
            <Popconfirm
              title={languageCode === 'CN' ? "确定要删除吗?" : 'You sure you want to delete it?'}
              onConfirm={this.delConfirm}
              okText={languageCode === 'CN' ? "是" : 'Yes'}
              cancelText={languageCode === 'CN' ? "否" : 'No'}
            >
              <span style={{ color: '#f00' }} className='span' onClick={() => this.setState({ delAdmReaConID: record.id })}><Icon type="delete" />{languageCode === 'CN' ? "删除" : 'Delete'}</span>
            </Popconfirm>
          </span>
        ),
      },
    )
  }
  onColumnRef = (ref) => {
    console.log(ref)
    this.columnRef = ref;
  }
  // 获取主列表columns
  tableList = (reactCode, compontName) => {
    var data = {
      params: [{
          "reactCode": [reactCode],
          "compontName": compontName,
          "type": "C"
      }]
  }
    console.log(1, data)
    $http.post('urlS', this, {
        code: '01040073',
        data: data,
        success: function (res) {
            if (+res.errorCode === 0) {
                let resC = res.result.C
                let { languageCode } = this.state
                for (var i = 0; i < resC.length; i++) {
                    resC[i].key = i;
                }
                if (languageCode === "EN") {
                    resC.map((item, i) => {
                        item.title = item.enDescripts
                    })
                }
            
                if (languageCode === "CN") {
                    resC.map((item, i) => {
                        item.title = item.descripts
                    })
                }
                let arr = res.result && resC.length > 0 ? JSON.parse(JSON.stringify(resC)).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' });
                this.setState({ 
                  columns: filterArr,
                  languageTable1: res.result.B || {},  // 国际化Table1
                  languageTable2: res.result.C || {},  // 国际化Table2
                  languageData: res.result.language || {},  // 国际化语言包
                }, () => {
                  this.LanCNEN(this.state.languageCode)
                  this.listAdd(filterArr.length+1, 0,languageCode);
                })
            }
        }
    })
  }

  LanCNEN = (code) => {
    let { languageData } = this.state
    this.setState({
        language: languageData[code]
    })
  }


  componentDidMount() {
    this.tableList("TypesOfVisitsAndFees","TypesOfVisitsAndFees");
    //初始化列表数据
    this.handleQuery();
    //医院下拉框
    this.getHospitalData();
    //就诊类型下拉框
    this.getAdmReacon();
    //病人费别下拉框
    this.getAdmReason();
  }

  //开始日期选择器选择限制
  disabledStartDate = startValue => {
    const { endValue } = this.state;
    if (!startValue || !endValue) {
      return false;
    }
    return startValue.valueOf() > endValue.valueOf();
  };

  //失效日期选择器选择限制
  disabledEndDate = endValue => {
    const { startValue } = this.state;
    if (!endValue || !startValue) {
      return false;
    }
    return endValue.valueOf() <= startValue.valueOf();
  };

  onChange = (field, value) => {
    this.setState({
      [field]: value,
    });
  };

  //开始日期变化
  onStartChange = value => {
    this.onChange('startValue', value);
  };

  //结束日期变化
  onEndChange = value => {
    this.onChange('endValue', value);
  };

  //初始化列表数据
  handleQuery = () => {
    let { page, pageSize, selectHosp, selectReaCon, selectReason } = this.state;
    let data = {}
    data = {
      params: [{
        hospID: selectHosp,
        admReaConDr: selectReaCon,
        admReasonDr: selectReason
      }],
      pagination: [{
        pageSize: pageSize,
        currentPage: page,
        sortColumn: 'code',
        sortOrder: 'asc'
      }]
    }
    $http.post('urlS', this, {
      code: '05100244',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0 && res.result) {
          for (var i = 0; i < res.result.length; i++) {
            res.result[i].key = i;
          }
          this.setState({ tableData: res.result.Data, total: res.result.TotalCount, loading: false })
        } else {
          this.setState({ tableData: [], total: 0, loading: false })
        }
      }
    })
  }

  //病人费别下拉框数据
  getAdmReason = () => {
    var data = {
      params: [{
        hospID: this.state.admReaSonHosp,
      }]
    }
    let admReasonDr = []
    $http.post("urlS", this, {
      code: '05100247',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0 && res.AdmReaSonArr) {
          for (var i = 0; i < res.AdmReaSonArr.length; i++) {
            admReasonDr.push(<Option value={String(res.AdmReaSonArr[i].ID)} >{res.AdmReaSonArr[i].AdmReaSon}</Option>)
          }
          this.setState({ admReasonDr: admReasonDr, Reason: admReasonDr, })
        }
      },
      error: function (err) {
        this.setState({ errMsg: "数据加载失败，请重试！" })
      }
    })
  }

  //删除确认
  delConfirm = (e) => {
    this.handleDel();
  }
  //就诊类型下拉框数据
  getAdmReacon = () => {
    var data = {
      params: []
    }
    let admReaConDr = []
    $http.post("urlS", this, {
      code: '05100246',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0 && res.AdmReaConArr) {
          for (var i = 0; i < res.AdmReaConArr.length; i++) {
            admReaConDr.push(<Option value={String(res.AdmReaConArr[i].ID)} >{res.AdmReaConArr[i].AdmReaCon}</Option>)
          }
          this.setState({ admReaConDr: admReaConDr, ReaCon: admReaConDr, })
        }
      },
      error: function (err) {
        this.setState({ errMsg: "数据加载失败，请重试！" })
      }
    })
  }

  //医院下拉框数据
  getHospitalData = () => {
    var data = {
      params: [{
        logonGroupID: JSON.parse(window.sessionStorage.userData).groupID,
        logonHospID: JSON.parse(window.sessionStorage.userData).hospID,
        dataType: "combo",
      }]
    }
    let hospital = []
    $http.post("urlS", this, {
      code: '05100046',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0 && res.Hosp) {
          for (var i = 0; i < res.Hosp.length; i++) {
            hospital.push(<Option value={String(res.Hosp[i].id)} key={i + "H"} >{res.Hosp[i].descripts}</Option>)
          }
          this.setState({ hospital: hospital, Hosp: hospital, })
        }
      },
      error: function (err) {
        this.setState({ errMsg: "数据加载失败，请重试！" })
      }
    })
  }

  //病人费别下拉框，医院查询 --- 查询条件
  onChangeHosp = (e) => {
    this.setState({ admReaSonHosp: e, selectHosp: e }, () => {
      this.setState({ selectReason: undefined }, () => {
        this.getAdmReason();
      })
    });
  }

  //弹窗医院下拉框初始化 --- 查询条件
  onChangeModalHosp = (e, type) => {
    if (type) {
      this.props.form.setFieldsValue({
        'Reason': '',
      });
    }
    this.setState({ admReaSonHosp: e }, () => {
      this.getAdmReason();
    });

  }

  //就诊类型 --- 查询条件
  onChangeReaCon = (e) => {
    this.setState({ selectReaCon: e });
  }

  //病人费别 --- 查询条件
  onChangeReason = (e) => {
    this.setState({ selectReason: e });
  }

  //弹窗显示
  showModal = (params) => {
    if (params === 'add') {
      this.setState({
        modalState: 'add',
        visible: true,
        motalTitle: "新增",
        startValue: null,
        endValue: null,
      });
      this.onChangeModalHosp(JSON.parse(window.sessionStorage.userData).hospID);
      this.props.form.setFieldsValue({
        'Hosp': JSON.parse(window.sessionStorage.userData).hospID,
        'ReaCon': '',
        'Reason': '',
        'StartDate': undefined,
        'StopDate': undefined,
        'IsDefault': false,
      });
    } else {
      this.setState({
        modalState: 'update',
        updateID: params.id,
        visible: true,
        motalTitle: "修改",
        startValue: moment(params.StartDate, 'YYYY-MM-DD'),
        endValue: params.StopDate ? moment(params.StopDate, 'YYYY-MM-DD') : null,
      });
      this.onChangeModalHosp(params.Hosp);
      this.props.form.setFieldsValue({
        'Hosp': params.Hosp,
        'ReaCon': params.AdmReaConDr,
        'Reason': params.AdmReasonDr,
        'StartDate': moment(params.StartDate, 'YYYY-MM-DD'),
        'StopDate': params.StopDate ? moment(params.StopDate, 'YYYY-MM-DD') : undefined,
        'IsDefault': params.IsDefault === 'Y' ? true : false,
      });
    }
  };

  //弹窗点击确定
  handleOk = () => {
    this.props.form.validateFields((err, values) => {
      if (err) {
        return;
      }
      let data = {};
      let code = '';
      if (this.state.modalState === 'add') {
        code = '05100249';
      } else if (this.state.modalState === 'update') {
        code = '05100251';
      }
      data = {
        params: [{
          ID: this.state.updateID,
          userID: JSON.parse(window.sessionStorage.userData).userID,
          createUserID: JSON.parse(window.sessionStorage.userData).userID,
          hospID: values.Hosp,
          admReaConID: values.ReaCon,
          admReasonID: values.Reason,
          startDate: moment(values.StartDate).utcOffset(480).format('YYYY-MM-DD'),
          stopDate: values.StopDate ? moment(values.StopDate).utcOffset(480).format('YYYY-MM-DD') : '',
          isDefault: values.IsDefault ? 'Y' : 'N',
        }]
      }
      $http.post('urlS', this, {
        code: code,
        data: data,
        success: function (res) {
          if (+res.errorCode === 0) {
            message.success(res.errorMessage);
            this.handleQuery();
            this.setState({ loading: false, visible: false });
          }
        }
      })
    })
  };

  //弹窗点击取消
  handleCancel = () => {
    this.setState({ visible: false, });
  };

  //删除操作
  handleDel = () => {
    let data = {
      params: [{
        admReaConID: this.state.delAdmReaConID,
        changeID: JSON.parse(window.sessionStorage.userData).userID
      }]
    };
    $http.post('urlS', this, {
      code: "05100250",
      data: data,
      success: function (res) {
        let errorCode = res.errorCode;
        if (errorCode === '0') {
          message.success(res.errorMessage);
          this.handleQuery() // 查询
        }
      }
    });
  }

  // 页码改变的回调，参数是改变后的页码及每页条数
  appPageChange = (page, pageSize) => {
    this.setState({
        page: page,
        pageSize: pageSize,
    }, () => {
        // 重新调用查询方法
        this.handleQuery();
    });
  }

  // 条数改变的回调
  apponShowSizeChange = (current, size) => {
    this.setState({
        page: current,
        pageSize: size,
    }, () => {
        // 重新调用查询方法
        this.handleQuery();
    });
  }

  render() {
    let { hospital, admReaConDr, admReasonDr, Hosp, ReaCon, Reason, startValue, endValue, language, languageCode} = this.state;
    // 医院
    const { getFieldDecorator } = this.props.form;
    return (
      <div>
        <div style={{ width: '100%', height: '100%' }}>
          <Row style={{ minHeight: '80px', padding: '24px 24px 24px 24px' }}>
            <Col span={6}>
              <span>{language.TypesOfVisitsAndFeeshosp && language.TypesOfVisitsAndFeeshosp.descripts}：</span>
              <Select style={{ width: '150px' }} value={this.state.selectHosp} allowClear placeholder={language.TypesOfVisitsAndFeeshosp && language.TypesOfVisitsAndFeeshosp.message} onChange={this.onChangeHosp} >
                {hospital}
              </Select>
            </Col>
            <Col span={6}>
              <span>{language.TypesOfVisitsAndFeesadmReaConDr && language.TypesOfVisitsAndFeesadmReaConDr.descripts}：</span>
              <Select style={{ width: '150px' }} allowClear placeholder={language.TypesOfVisitsAndFeesadmReaConDr && language.TypesOfVisitsAndFeesadmReaConDr.message} onChange={this.onChangeReaCon} >
                {admReaConDr}
              </Select>
            </Col>
            <Col span={6}>
              <span>{language.TypesOfVisitsAndFeesadmReasonDr && language.TypesOfVisitsAndFeesadmReasonDr.descripts}：</span>
              <Select style={{ width: '150px' }} allowClear value={this.state.selectReason} placeholder={language.TypesOfVisitsAndFeesadmReasonDr && language.TypesOfVisitsAndFeesadmReasonDr.message} onChange={this.onChangeReason} >
                {admReasonDr}
              </Select>
            </Col>
            <Col span={3} style={{ textAlign: 'right' }}>
              <Button type="primary" onClick={() => this.handleQuery()} icon="search" >{language.TypesOfVisitsAndFeeshandleQuery && language.TypesOfVisitsAndFeeshandleQuery.descripts}</Button>
            </Col>
            <Col span={3} style={{ textAlign: 'center' }}>
              <Button type="primary" onClick={() => this.showModal('add')} icon="plus" style={{ background: '#F7805D', color: '#FFFFFF', borderColor: '#F7805D' }} >
                {language.TypesOfVisitsAndFeesshowModal && language.TypesOfVisitsAndFeesshowModal.descripts}
              </Button>
              <Form layout="inline">
                <Modal
                  visible={this.state.visible}
                  title={this.state.motalTitle}
                  onOk={() => this.handleOk(this.state.modalState)}
                  onCancel={this.handleCancel}
                  width='600px'
                  footer={[
                    <Button key="back" onClick={this.handleCancel}>
                      {language.TypesOfVisitsAndFeeshandleCancel && language.TypesOfVisitsAndFeeshandleCancel.descripts}
                    </Button>,
                    <Button key="submit" type="primary" loading={this.state.loading} onClick={this.handleOk}>
                      {language.TypesOfVisitsAndFeeshandleOk && language.TypesOfVisitsAndFeeshandleOk.descripts}
                    </Button>,
                  ]}
                >
                  <Row>
                    <Col span={24}>
                      <Form.Item label={language.TypesOfVisitsAndFeeshosp && language.TypesOfVisitsAndFeeshosp.descripts} {...formItemLayout} >
                        {getFieldDecorator("Hosp", {
                          initialValue: '',
                        })(
                          <Select style={{ width: '150px' }} allowClear placeholder={language.TypesOfVisitsAndFeeshosp && language.TypesOfVisitsAndFeeshosp.message} onChange={(e) => this.onChangeModalHosp(e, 'keuUp')} >
                            {Hosp}
                          </Select>
                        )}
                      </Form.Item>
                    </Col>
                    <Col span={24}>
                      <Form.Item label={language.TypesOfVisitsAndFeesreaCon && language.TypesOfVisitsAndFeesreaCon.descripts} {...formItemLayout}>
                        {getFieldDecorator("ReaCon", {
                          initialValue: '',
                          rules: [{ required: true, message: languageCode === 'CN' ? "就诊类型不能为空" : 'Reacon cannot be empty' }]
                        })(
                          <Select style={{ width: '150px' }} allowClear placeholder={language.TypesOfVisitsAndFeesreaCon && language.TypesOfVisitsAndFeesreaCon.message} >
                            {ReaCon}
                          </Select>
                        )}
                      </Form.Item>
                    </Col>
                    <Col span={24}>
                      <Form.Item label={language.TypesOfVisitsAndFeesreason && language.TypesOfVisitsAndFeesreason.descripts} {...formItemLayout}>
                        {getFieldDecorator("Reason", {
                          initialValue: '',
                          rules: [{ required: true, message: languageCode === 'CN' ? "病人费别不能为空" : 'Reason cannot be empty' }]
                        })(
                          <Select style={{ width: '150px' }} allowClear placeholder={language.TypesOfVisitsAndFeesreason && language.TypesOfVisitsAndFeesreason.message} >
                            {Reason}
                          </Select>
                        )}
                      </Form.Item>
                    </Col>
                    <Col span={24}>
                      <Form.Item label={language.TypesOfVisitsAndFeesstartDate && language.TypesOfVisitsAndFeesstartDate.descripts} {...formItemLayout}>
                        {getFieldDecorator("StartDate", {
                          initialValue: undefined,
                          rules: [{ required: true, message: languageCode === 'CN' ? "开始日期不能为空" : 'Start Date cannot be empty'}]
                        })(
                          <DatePicker
                            format={dateFormat}
                            disabledDate={this.disabledStartDate}
                            value={startValue}
                            onChange={this.onStartChange}
                          />
                        )}
                      </Form.Item>
                    </Col>
                    <Col span={24}>
                      <Form.Item label={language.TypesOfVisitsAndFeesstopDate && language.TypesOfVisitsAndFeesstopDate.descripts} {...formItemLayout}>
                        {getFieldDecorator("StopDate", {
                          initialValue: undefined,
                        })(
                          <DatePicker
                            format={dateFormat}
                            disabledDate={this.disabledEndDate}
                            value={endValue}
                            onChange={this.onEndChange}
                          />
                        )}
                      </Form.Item> 
                    </Col>
                    <Col span={24}>
                      <Form.Item label="是否默认" {...formItemLayout}>
                        {getFieldDecorator("IsDefault", {
                          valuePropName: 'checked',
                          initialValue: false,
                        })(
                          <Switch checkedChildren="是" unCheckedChildren="否" />
                        )}
                      </Form.Item>
                    </Col>
                  </Row>
                </Modal>
              </Form>
            </Col>
          </Row>
        </div>
        <div style={{ widht: '100%', height: '10px', background: '#f0f2f5' }}></div>
        <div style={{ padding: 24 }}>
          {/* handelThis将父组件的属性与方法给子组件访问 */}
          {/* <PubilcTablePagination param={param} handelThis={this} onRef={this.onRef} /> */}
          <Table
              style={{ height: store.getState().tableHeight.y + 65 + 'px' }}
              dataSource={this.state.tableData}
              columns={this.state.columns}  
              className='TableA'
              //rowClassName="editable-row"
              pagination={false}
              scroll={{ x: 900, y: store.getState().tableHeight.y }}
              bordered
              loading={this.state.loading}
          />
          <CommonPagination size="small" current={this.state.page} total={this.state.total} search='search'
              onShowSizeChange={this.apponShowSizeChange} complete={true} dataSource={this.state.tableData}
              onChange={this.appPageChange} />
          <ColumnAuthoritysModel
              clientWidth='800px'
              compontName='TypesOfVisitsAndFees'
              configType="C"
              onRef={this.onColumnRef}
              reloadData={this.tableList}
          />
        </div>
      </div>
    )
  }
}


const OPAdmReaConForm = Form.create()(OPAdmReaCon);
export default OPAdmReaConForm;
