import React from 'react';
import { Table, Modal, Select, message, Input, Form, Row, Col, Button, DatePicker } from 'antd';
import { $http } from 'containers/config/https';
import PubilcTablePagination from '../common/PubilcTablePagination.jsx'; // 公共table组件
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: 16, offset: 0 },
};


class InvDeliver extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false, //加载状态标志
      tableData: [], // 表格数据
      visible: false, //弹窗显示标志
      total: 0,  // 表格数据总条数
      page: 1, //当前页数
      pageSize: 10, //每页显示条数
      startValue: null, //日期选择器开始时间
      endValue: null, //日期选择器结束时间

      useUseName: '', //领取人
      stDate: '', //开始时间
      endDate: '', //结束时间
      prefix: '', //前缀
      invState: '', //发票状态
      invTypeID: '', //发票类型ID
      invList: [], //发票类型数据
      userList: [], //领取人员数据
      inputUserList: [], //弹窗领取人员数据

      modalStartNo: '', //弹窗默认显示开始号码
      modalEndNo: '', //弹窗默认显示结束号码
      selectUseUseName: undefined, //弹窗领取人默认值
      transID: '', //记录ID
      isSubmit: true,

      columns: [],
      languageTable1: {}, // 国际化Table1
      languageTable2: {}, // 国际化Table2
      languageData: {}, // 国际化语言包
      language: {},   // 国际化语言
      languageCode: JSON.parse(window.sessionStorage.userData).language, // 国际化语言标识
    };
    // this.columns = [
    //   {
    //     title: '发票类型',
    //     dataIndex: 'InvTypeDesc',
    //     key: 'InvTypeDesc',
    //     align: "center",
    //     width: "110px",
    //   },
    //   {
    //     title: '领取人',
    //     dataIndex: 'UseUseName',
    //     key: 'UseUseName',
    //     align: "center",
    //     width: "100px",
    //   },
    //   {
    //     title: '开始号码',
    //     dataIndex: 'StartNo',
    //     key: 'StartNo',
    //     align: "center",
    //     width: "100px",
    //   },
    //   {
    //     title: '结束号码',
    //     dataIndex: 'EndNo',
    //     key: 'EndNo',
    //     align: "center",
    //     width: "100px",
    //   },
    //   {
    //     title: '当前号码',
    //     dataIndex: 'CurrentNo',
    //     key: 'CurrentNo',
    //     align: "center",
    //     width: "100px",
    //   },
    //   {
    //     title: '前缀',
    //     dataIndex: 'Prefix',
    //     key: 'Prefix',
    //     align: "center",
    //     width: "80px",
    //   },
    //   {
    //     title: '状态',
    //     dataIndex: 'Avilable',
    //     key: 'Avilable',
    //     align: "center",
    //     width: "80px",
    //   },
    //   {
    //     title: '转交人/接收人',
    //     dataIndex: 'TransUseUserName',
    //     key: 'TransUseUserName',
    //     align: "center",
    //     width: "80px",
    //   },
    //   {
    //     title: '转交日期',
    //     dataIndex: 'GrantDate',
    //     key: 'GrantDate',
    //     align: "center",
    //     width: "100px",
    //   },
    //   {
    //     title: '医院',
    //     dataIndex: 'HospDesc',
    //     key: 'HospDesc',
    //     align: "center",
    //     width: "200px",
    //   },
    //   {
    //     title: '操作',
    //     key: 'op',
    //     align: "center",
    //     width: "80px",
    //     render: (text, record) => (
    //       <span>
    //         {record.AvilableCode === 'N' ? <span>移交发票</span> : <span className='span' onClick={() => this.showModal(record)}>转交发票</span>}
    //       </span>
    //     ),
    //   },
    // ];
  }

  componentDidMount() {
    this.tableList();
    //发票类型数据
    this.invTypeData();
    //初始化列表数据
    this.handleQuery();
  }
  //render 自定义项目名称
  listAdd = (i, j, languageCode) => {
    let { columns } = this.state
    columns.splice(i, j,
      {
        title: languageCode === 'CN' ? "操作" : 'Operation',
        key: 'op',
        align: "center",
        width: "100px",
        render: (text, record) => (
          <span>
            {record.AvilableCode === 'N' ? <span>{languageCode === 'CN' ? "移交发票" : 'Hand Invoice'}</span> : <span className='span' onClick={() => this.showModal(record)}>{languageCode === 'CN' ? "转交发票" : 'Deliver Invoice'}</span>}
          </span>
        ),
      },
    )
  }
  onColumnRef = (ref) => {
    console.log(ref)
    this.columnRef = ref;
  }
  // 获取主列表columns
  tableList = (reactCode, compontName) => {
    var data = {
      params: [{
        "reactCode": ["InvDeliver"],
        "compontName": "InvDeliver",
        "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]
    })
  }
  //发票类型数据
  invTypeData = () => {
    let data = {}
    data = {
      params: [{
        code: "",
        descripts: ""
      }]
    }
    $http.post('urlS', this, {
      code: '5001',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0 && res.invType) {
          let tempList = this.state.invList
          for (var i = 0; i < res.invType.length; i++) {
            tempList.push(<Option key={res.invType[i].ID}>{res.invType[i].Descripts}</Option>)
          }
          this.setState({
            invList: tempList
          })
        }

      }
    })
  }

  //初始化列表数据
  handleQuery = () => {
    let { page, pageSize, invTypeID, useUseName, startValue, endValue, prefix, invState } = this.state;
    let data = {}
    data = {
      params: [{
        invTypeID: invTypeID,
        userID: useUseName,
        endDate: endValue,
        stDate: startValue,
        prefix: prefix,
        hospID: JSON.parse(window.sessionStorage.userData).hospID,
        status: invState
      }],
      pagination: [{
        pageSize: pageSize,
        currentPage: page,
        sortColumn: "Code",
        sortOrder: "asc"
      }]
    }
    $http.post('urlS', this, {
      code: '05100051',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0 && res.grant) {
          for (var i = 0; i < res.grant.length; i++) {
            res.grant[i].key = i;
          }
          this.setState({ tableData: res.grant, total: res.total, loading: false })
        }
      }
    })
    // 数据加载成功关闭loading
    //this.child.handleLoading()
  }

  //查询条件 --- 发票类型
  onChangeInvType = (value, type) => {
    if (type) {
      this.props.form.setFieldsValue({
        'UseUseName': undefined,
      });
    }
    if (value === '') {
      this.setState({ invTypeID: value, userList: [] });
    } else {
      this.setState({ invTypeID: value, userList: [], }, () => {
        this.handleUserQuery("select");
      });
    }
  }

  //查询条件 --- 发票状态
  onChangeInvState = (value) => {
    this.setState({ invState: value });
  }

  //查询条件 --- 前缀
  onChangePrefix = (e) => {
    this.setState({ prefix: e.target.value });
  }

  //查询条件 --- 领取人
  onChangeUseUseName = (value) => {
    this.setState({
      useUseName: value,
    });
  }

  //领取人员下拉框
  handleUserQuery = (type) => {
    let { invTypeID } = this.state;
    //获取sessionStorage的数据
    let sessionInfo = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
    //obj.createUserDr =sessionInfo.userId;
    //obj.updateUserDr =sessionInfo.userId;
    //obj.hospDr=sessionInfo.hospDr;
    let data = {}
    data = {
      params: [{
        hospID: sessionInfo.hospID,
        userType: "3",
        invTypeID: invTypeID
      }]
    }
    $http.post('urlS', this, {
      code: '05100053',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0 && res.invUserInfo) {
          let tempList = []
          for (var i = 0; i < res.invUserInfo.length; i++) {
            tempList.push(<Option key={res.invUserInfo[i].id} alias={res.invUserInfo[i].descriptsSPCode}>{res.invUserInfo[i].descripts}</Option>)
          }
          if (type === 'select') {
            this.setState({
              userList: tempList
            })
          } else {
            this.setState({
              inputUserList: tempList
            })
          }
        }
      }
    })
  }

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

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

  //开始日期选择器选择限制
  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);
  };

  //弹窗领取人变化
  onChangeModalUseUseName = (value) => {
    this.setState({
      selectUseUseName: value,
      isSubmit: value ? false : true,
    });
  }

  //弹窗显示
  showModal = (record) => {
    this.setState({
      visible: true,
      selectUseUseName: undefined,
      modalStartNo: record.StartNo,
      modalEndNo: record.EndNo,
      transID: record.GrantID,
      isSubmit: true,
      invTypeID: record.InvTypeDr,
    }, () => {
      this.handleUserQuery("input");
    });
  };

  //弹窗点击确定
  handleOk = () => {
    let { isSubmit } = this.state
    if (isSubmit) {
      return;
    } else {
      let data = {};
      data = {
        params: [{
          userID: JSON.parse(window.sessionStorage.userData).userID,
          useUserID: this.state.selectUseUseName,
          transID: this.state.transID,
        }]
      }
      $http.post('urlADS', this, {
        code: '05100300',
        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, });
  };

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

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

  render() {
    let { startValue, endValue, invList, userList, language, languageCode } = this.state;
    const { getFieldDecorator } = this.props.form;
    const param = {
      // 表头配置
      columns: this.columns,
      // 表格数据
      data: this.state.tableData,
      // 数据总条数
      total: this.state.total,
      // 数据页数
      page: 1,
      // 表格的宽度
      x: 1300,
    }
    return (
      <div>
        <div style={{ minHeight: '80px', width: '100%', height: '100%', padding: '24px 24px 24px 24px' }}>
          <Row>
            <Col span={6}>
              <Form.Item label={language.InvDeliverInvType && language.InvDeliverInvType.descripts} {...formItemLayout} >
                {getFieldDecorator("InvType", {
                  initialValue: undefined,
                })(
                  <Select style={{ width: '150px' }} allowClear onChange={(value) => this.onChangeInvType(value, 'keuUp')} placeholder={language.InvDeliverInvType && language.InvDeliverInvType.message} >
                    {invList}
                  </Select>
                )}
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item label={language.InvDeliverInvState && language.InvDeliverInvState.descripts} {...formItemLayout} >
                {getFieldDecorator("InvState", {
                  initialValue: undefined,
                })(
                  <Select style={{ width: '150px' }} allowClear onChange={(value) => this.onChangeInvState(value)} placeholder={language.InvDeliverInvState && language.InvDeliverInvState.message} >
                    <Option value="1">{languageCode === "CN" ? '可用' : 'Available'}</Option>
                    <Option value="2">{languageCode === "CN" ? '待用' : 'To Be Use'}</Option>
                    <Option value="3">{languageCode === "CN" ? '已用完' : 'Used Up'}</Option>
                    <Option value="4">{languageCode === "CN" ? '已退回' : 'Returned'}</Option>
                  </Select>
                )}
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item label={language.InvDeliverPrefix && language.InvDeliverPrefix.descripts} {...formItemLayout} >
                {getFieldDecorator("Prefix", {
                  initialValue: undefined,
                })(
                  <Input
                    style={{ width: '150px' }}
                    allowClear
                    placeholder={language.InvDeliverPrefix && language.InvDeliverPrefix.message}
                    onChange={(e) => this.onChangePrefix(e)}
                  />,
                )}
              </Form.Item>
            </Col>
            <Col span={6} style={{ textAlign: 'left' }}>
              <Button type="primary" onClick={() => this.handleQuery()} icon="search" >{languageCode === "CN" ? '查询' : 'Query'}</Button>
            </Col>
          </Row>
          <Row>
            <Col span={6}>
              <Form.Item label={language.InvDeliverStartDate && language.InvDeliverStartDate.descripts} {...formItemLayout}>
                {getFieldDecorator("StartDate", {
                  initialValue: undefined,
                })(
                  <DatePicker
                    format={dateFormat}
                    disabledDate={this.disabledStartDate}
                    value={startValue}
                    onChange={this.onStartChange}
                  />
                )}
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item label={language.InvDeliverEndDate && language.InvDeliverEndDate.descripts} {...formItemLayout}>
                {getFieldDecorator("StopDate", {
                  initialValue: undefined,
                })(
                  <DatePicker
                    format={dateFormat}
                    disabledDate={this.disabledEndDate}
                    value={endValue}
                    onChange={this.onEndChange}
                  />
                )}
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item label={language.InvDeliverRecipients && language.InvDeliverRecipients.descripts} {...formItemLayout} >
                {getFieldDecorator("UseUseName", {
                  initialValue: undefined,
                })(
                  <Select style={{ width: '150px' }} onChange={(value) => this.onChangeUseUseName(value)} allowClear placeholder={language.InvDeliverRecipients && language.InvDeliverRecipients.message} >
                    {userList}
                  </Select>
                )}
              </Form.Item>
            </Col>
          </Row>
          <Modal
            visible={this.state.visible}
            title={language.InvDeliverNewInvoiceTransfer && language.InvDeliverNewInvoiceTransfer.descripts}
            onOk={() => this.handleOk()}
            onCancel={this.handleCancel}
            width='600px'
            footer={[
              <Button key="back" onClick={this.handleCancel}>
                {languageCode === "CN" ? '取消' : 'Cancel'}
              </Button>,
              <Button key="submit" type="primary" loading={this.state.loading} onClick={this.handleOk}>
                {languageCode === "CN" ? '确认' : 'Confirm'}
              </Button>,
            ]}
          >
            <Row>
              <Col span={24} style={{ height: '50px' }}>
                <Col span={8} style={{ textAlign: 'right', }}>
                  <span>{language.InvDeliverStartNumber && language.InvDeliverStartNumber.descripts}：</span>
                </Col>
                <Col span={2}></Col>
                <Col span={14}>
                  <Input
                    disabled
                    style={{ width: '200px', }}
                    value={this.state.modalStartNo}
                  />
                </Col>
              </Col>
              <Col span={24} style={{ height: '50px' }}>
                <Col span={8} style={{ textAlign: 'right', }}>
                  <span>{language.InvDeliverEndNumber && language.InvDeliverEndNumber.descripts}：</span>
                </Col>
                <Col span={2}></Col>
                <Col span={14}>
                  <Input
                    disabled
                    style={{ width: '200px', }}
                    value={this.state.modalEndNo}
                  />
                </Col>
              </Col>
              <Col span={24}>
                <Col span={8} style={{ textAlign: 'right', }}>
                  <span style={{ display: 'inline-block', marginRight: '4px', color: '#f5222d', fontSize: '14px', lineHeight: 1, }}>*</span>
                  <span>{language.InvDeliverModalRecipients && language.InvDeliverModalRecipients.descripts}：</span>
                </Col>
                <Col span={2}></Col>
                <Col span={14}>
                  <Select style={{ width: '200px' }} value={this.state.selectUseUseName} onChange={(value) => this.onChangeModalUseUseName(value)} allowClear placeholder={language.InvDeliverModalRecipients && language.InvDeliverModalRecipients.message} >
                    {this.state.inputUserList}
                  </Select>
                </Col>
              </Col>
            </Row>
          </Modal>

        </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='900px'
            compontName='InvDeliver'
            configType="C"
            onRef={this.onColumnRef}
            reloadData={this.tableList}
          />
        </div>
      </div>
    )
  }
}

const InvDeliverForm = Form.create()(InvDeliver);
export default InvDeliverForm;