/*
 * Creator:     ML
 * CreatDate:   2019-09-19
 * descripts：卡类型管理
 * */
import React from 'react';
import { Form, Row, Col, Input, Select, Button, DatePicker,Popconfirm, Modal, Table, Icon, Pagination, message, Divider, Tooltip } from 'antd';
import moment from 'moment';
import { $http } from '../../containers/config/https';
import store from '../../store';
import './css/error.less';
import CardTypeModal from './component/CardTypeModal';
import CommonPagination from 'components/pagination/index';


const FormItem = Form.Item;
const Option = Select.Option;
const confirm = Modal.confirm;
const userData = sessionStorage.userData ? JSON.parse(sessionStorage.userData) : {}

let timer = undefined;

const formItemLayout = { // label 和input宽度
  labelCol: { span: 8 },
  wrapperCol: { span: 14 },
}

const formItemLayoutBind = { // label 和input宽度
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
}

const formItemcardStatus = {
  labelCol: { span: 7 },
  wrapperCol: { span: 14 },
}

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

const formItemMoney = {
  labelCol: { span: 11 },
  wrapperCol: { span: 11 },
}

const formItemCard = {
  labelCol: { span: 10 },
  wrapperCol: { span: 23 },
}

const formItemNewCard = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
}

const formItemNew = {
  labelCol: { span: 2 },
  wrapperCol: { span: 16 },
}

const formItemNewButton = {
  labelCol: { span: 2 },
  wrapperCol: { span: 22 },
}

const CardTypeManagement = Form.create()(
  class CardTypeManagement extends React.Component {
    constructor(props) {
      super(props)
      this.state = {
        loading: false,
        visible: false,
        baseParms: [],//下拉框数据
        total: 0,//表格总数据
        cardData: [],//查询出来的卡数据
        values: {},//查询条件数据
     
        searchLoading: false,//查询请求
        initCard: '',
        rowIds: '',//表格行选中 页面数据
        bindVail: true,//点击绑定前是否通过验证
        bindLoading: false,//点击绑定loading
        headerHeight:"",
        page:1,
        pageSize:20,
        size:"small",
        search:""
      }
    }
    componentDidMount() {
      let self = this
      // 初始化设置table的高度以及表体的高度
      document.querySelector('.ant-table-body').style.height = store.getState().tableHeight.y + 84 + 'px';
      let box = document.querySelector(".department-header");
      if(box){ //此处在加一层判断，更加严密，如果box存在的情况下获取
        this.setState({headerHeight: box.offsetHeight})
      }
      this.getCardTypeMan()
      this.getFindDate()
    }
    getCardTypeMan=()=>{
        let data = {}
        data = {
          params: [{
            userID:JSON.parse(sessionStorage.userData).userID || '',
            hospID:JSON.parse(sessionStorage.userData).hospID || '',
            groupID:JSON.parse(sessionStorage.userData).groupID || '',
          }],
        }
        $http.post('urlS', this, {
          code: '01040098',
          data: data,
          success: function (res) {
            if (+res.errorCode === 0 && res.result) {
              this.setState({ baseParms: res.result }, () => {
              })
            }
          }
        })
    }
    // 修改page和pageSize 跳转至---
    onChange = (e, pageSize) => {
      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} 条`;
    }
    //定位到最新添加/当前修改的记录
    getNewCard=(id)=>{
        //跳至最后一页 并定位到刚添加的这条记录
        if(id){
        let lastPage = Math.ceil((this.state.total + 1) / this.state.pageSize)
        this.onChange(lastPage, this.state.pageSize)    
        this.setState({
            rowIds:id
        })   
        }else{
            this.onChange(this.state.page, this.state.pageSize)   
        }
        
    }
    //获取查询数据
    getFindDate = (values,e) => {
      if (this.state.total == 0) {
        this.setState({
          searchLoading: true
        })
      }
      let { page, pageSize, } = this.state;
      let data = {}
      data = {
        params: [{
            // userID: "60",
            // hospID: "1",
            // groupID: "231",
            userID:JSON.parse(sessionStorage.userData).userID || '',
            hospID:JSON.parse(sessionStorage.userData).hospID || '',
            groupID:JSON.parse(sessionStorage.userData).groupID || '',
            searchCode: values&&values.number || '',
            selectHospID: values&&values.hospID||"",
        }],
        pagination: [{
          pageSize: pageSize,
          currentPage: page,
        }]
      }
      $http.post('urlS', this, {
        code: '01040097',
        data: data,
        success: function (res) {
          if (+res.errorCode === 0 && res.result) {
            this.setState({
              searchLoading: false,
              search:e
            })
            for (var i = 0; i < res.result.data.length; i++) {
              res.result.data[i].key = i + 'card'
            }
            this.setState({ cardData: res.result.data, total: res.result.totalCount, }, () => {
            })
          }else {
            this.setState({
              searchLoading: false
            })
          }
          if(res.result.data&&res.result.data.length==0&&res.result.totalCount>0){
            let prevPage = this.state.page - 1
            this.onChange(prevPage, this.state.pageSize)
          }
        },
        error: function () {
          this.setState({
            searchLoading: false
          })
        }
      })

    }
    //点击查询---卡列表
    findCard = () => {
      this.props.form.validateFields((err, values) => {
        if (!err) {
          this.setState({
            values: values,
            rowIds: ""
          })
          // this.setState({ page: 1, pageSize: 10 }, () => {
          //   let { values } = this.state;
            // this.getFindDate(values) 
            this.onShowSizeChange("1",this.state.pageSize)
          // })
        }
      })
    }
    // 调用子组件的连接事件 -- 添加新的卡类型
    OnChildrefs = (ref) => {
        this.child = ref
    }
    addCard=()=>{
        this.child.showModal()
    }
    //点击查询后 表格行
    setRowClassNames = (record) => {
      return record.id === this.state.rowIds ? 'clickRowStyle' : '';
    }
    //点击Row
    onClickRow = (record) => {
      return {
        onClick: () => {
          this.setState({
            parms: record,
          })
          if (this.state.rowId === "") {
            this.setState({
              rowIds: record.id,
            });
          } else {
            if (this.state.rowId !== record.id) {
              this.setState({
                rowIds: record.id,
              });
            } else {
              this.setState({
                rowIds: "",
                detailInfo: {},
              });
            }
          }
        },
      };
    }

    //选择查询卡类型
    patCardType = (data) => {
      if(this.state.baseParms&&this.state.baseParms.cardType.length>0){
        for (var i = 0; i < this.state.baseParms.cardType.length; i++) {
          if (data == this.state.baseParms.cardType[i].id) {
            this.setState({
              patReplenishZero: this.state.baseParms.cardType[i].replenishZero,
              patCardLength: this.state.baseParms.cardType[i].cardLength
            })
          }
        }
      }
    }
  
    //编辑 /删除 卡类型
    toggleEditable=(record,num)=>{
        if(num=="1"){
            this.child.showModal(record,num)
        }else{
            let arr = []
            arr.push(record.id)
            let datas = {}
            datas = {
              params: [{
                  userID:JSON.parse(sessionStorage.userData).userID || '',
                  hospID:JSON.parse(sessionStorage.userData).hospID || '',
                  groupID:JSON.parse(sessionStorage.userData).groupID || '',
                  id:arr,
                // "userID": "60",
                // "hospID": "1",
                // "groupID": "231",
              }],
            }
            $http.post('urlS', this, {
              code: '01040096',
              data: datas,
              success: function (res) {
                if (+res.errorCode === 0) {
                  message.success("删除成功");
                  this.getFindDate()
                }
              }
            })
          }
    }

    render() {
      const { getFieldDecorator } = this.props.form;
      const {  baseParms, searchLoading,  bindLoading } = this.state;
      const mesIcon = <Icon type="exclamation-circle" />
      //医院
      let hosptilOption = []
      baseParms.hosp && baseParms.hosp.map(item => {
        hosptilOption.push(<Option key={item.id}  value={item.id} title={item.descripts}>{item.descripts}</Option>)
      })
      
      //主页面查询结果表格
      const columns = [
        {
          title: '医院',
          dataIndex: 'selectHospDesc',
          width: 180,
          key: '0',
          align: "center",
        }, {
          title: '代码',
          dataIndex: 'code',
          width: 120,
          align: "center",
          key: '1'
        }, {
          title: '类型名称',
          dataIndex: 'descripts',
          width: 100,
          align: "center",
          key: '2'
        }, {
          title: '是否收费',
          dataIndex: 'repariFeeFlag',
          width: 200,
          align: "center",
          key: '3'
        }, {
          title: '是否打印发票',
          dataIndex: 'INVFlag',
          width: 100,
          align: "center",
          key: '4',
          render: (text, record, index) => {
            if (text == "Y") {
              text = "是"
              return text
            } if (text == "N") {
              text = "否"
              return text
            }
            return text;
          },
        }, {
          title: '发票类别',
          dataIndex: 'INVTypeDesc',
          width: 140,
          align: "center",
          key: '5'
        }, {
          title: '卡校验',
          dataIndex: 'verifyFlag',
          width: 150,
          align: "center",
          key: '6',
          render: (text, record, index) => {
            if (text == "Y") {
              text = "校验"
              return text
            } if (text == "N") {
              text = "不校验"
              return text
            }
            return text;
          },
        }, {
          title: '是否回收',
          dataIndex: 'retrieveFlag',
          width: 100,
          align: "center",
          key: '7',
          render: (text, record, index) => {
            if (text == "Y") {
              text = "是"
              return text
            } if (text == "N") {
              text = "否"
              return text
            }
            return text;
          },
        }, {
          title: '是否换卡',
          dataIndex: 'changeFlag',
          width: 100,
          align: "center",
          key: '8',
          render: (text, record, index) => {
            if (text == "Y") {
              text = "是"
              return text
            } if (text == "N") {
              text = "否"
              return text
            }
            return text;
          },
        }, {
          title: '是否补卡',
          dataIndex: 'repairFlag',
          width: 100,
          align: "center",
          key: '9',
          render: (text, record, index) => {
            if (text == "Y") {
              text = "是"
              return text
            } if (text == "N") {
              text = "否"
              return text
            }
            return text;
          },
        }, {
          title: '是否写卡',
          dataIndex: 'writeFlag',
          width: 100,
          align: "center",
          key: '10',
          render: (text, record, index) => {
            if (text == "Y") {
              text = "是"
              return text
            } if (text == "N") {
              text = "否"
              return text
            }
            return text;
          },
        },{
          title: '操作',
          dataIndex: 'cardStatus2',
          width: 100,
          align: "center",
          key: 'cardStatus2',
          render: (text, record) => (
            <span>
                <a onClick={(e) => this.toggleEditable(record, "1")}>编辑</a>
                <Divider type="vertical" />
                <Popconfirm title="是否要删除此行" onConfirm={() => this.toggleEditable(record, "2")}>
                  <a style={{ color: "red" }} >删除</a>
                </Popconfirm>
              </span>
          ),
        }]
      return (
          <div style={{ padding: '4px 2px' }} className="cardListDom">
          <div className="department-header">
            <Form>
              <Row gutter={60} style={{ margin: '0' }}>
                <Col span={5}>
                  <FormItem label='医院名称' {...formItemLayout}>
                    {getFieldDecorator('hospID', {
                      initialValue: undefined,
                      rules: [{ required: false, message: '' }],
                    })(
                      <Select showSearch allowClear optionFilterProp="title" placeholder='请选择医院' style={{ width: '100%' }} >
                        {hosptilOption}
                      </Select>
                    )}
                  </FormItem>
                </Col>
                <Col span={9} style={{ marginLeft: '-60px' }}>
                  <FormItem label='类型名称/代码' {...formItemNumber}>
                    {getFieldDecorator('number', {
                      initialValue: undefined,
                      rules: [{ required: false, message: '' }],
                    })(
                      <Input placeholder='输入名称/代码可模糊查询' allowClear onPressEnter={this.findCard} />
                    )}
                  </FormItem>
                </Col>
                <Col span={2} style={{ marginLeft: '-60px' }}>
                  <FormItem  {...formItemLayout}>
                    {getFieldDecorator('posInp', {
                      initialValue: undefined,
                      rules: [{ required: false, message: '' }],
                    })(
                      <Button onClick={this.findCard} loading={searchLoading} style={{ background: 'rgba(66,185,131,1)', color: '#fff' }}>查询</Button>
                    )}
                  </FormItem>
                </Col>
                <Col span={2} style={{ marginLeft: '-60px' }}>
                  <FormItem  {...formItemLayout}>
                    {getFieldDecorator('addNewCard', {
                      initialValue: undefined,
                      rules: [{ required: false, message: '' }],
                    })(
                      <Button onClick={this.addCard} style={{ background: 'rgba(66,185,131,1)', color: '#fff' }}>+新类型</Button>
                    )}
                  </FormItem>
                </Col>
              </Row>
            </Form>
            </div>
            <div>
              <Table
                scroll={{ x: 1160, y: store.getState().tableHeight.y + 156 }}
                columns={columns}
                dataSource={this.state.cardData}
                pagination={false}
                rowKey={record => record.key}
                onRow={this.onClickRow}
                rowClassName={this.setRowClassNames}
                bordered
                style={{ height: store.getState().tableHeight.y + 134  +  'px' }}
              />
               <CommonPagination size={this.state.size} pageSize={this.state.pageSize} current={this.state.page} total={this.state.total} search={this.state.search}
                    onShowSizeChange={this.onShowSizeChange.bind(this)} complete={true} dataSource={this.state.cardData}
                    onChange={this.onChange.bind(this)} />
                   
              {/* {
               this.state.cardData&&this.state.cardData.length>0?<Pagination
                showTotal={() => this.showTotal(this.state.total)}
                size="small"
                showQuickJumper
                showSizeChanger
                defaultCurrent={1}
                current={this.state.page ? this.state.page : 1}
                total={this.state.total ? this.state.total : 0}
                onChange={this.onChange}
                onShowSizeChange={this.onShowSizeChange}
                style={{ textAlign: "right", }}
              />:""
              } */}
            </div>
            <CardTypeModal getNewCard={this.getNewCard}  OnChildrefs={this.OnChildrefs}></CardTypeModal>
          </div>
      )
    }
  })
export default CardTypeManagement    