import React from 'react';
import { Table, Input, Button, Divider, Popconfirm, message, Select } from 'antd';
import '../../assets/css/system.css';
import store from '../../store';
import CommonPagination from 'components/pagination/index';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import { $http } from '../../containers/config/https';
import PersonRelatedInvTypeModal from './PersonRelatedInvTypeModal.jsx';
const Option = Select.Option;

export default class PersonRelatedInvType extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      // 抽屉显示
      columns: [],
      visible: false,
      // 主菜单分页数据
      total: 0,
      page: 1,
      pageSize: 10,
      flag: '',
      title: '',
      // 是否显示loading
      showLoading: true,
      // 表格loading
      loading: true,
      //查询条件数据
      userType: '',
      userInfo: {},
      // 主菜单列表数据
      data: [],
      //发票类型下拉框数据
      invList: [],
      invTypeID: '',
      userList: [],
      userID: '',
      hospList: [],
      hospID: '',
      //权限已经在后端判断前端全置为1在控制
      addPower: 1,
      deletePower: 1,
      updatePower: 1,
      findPower: 1,
      languageTable1: {}, // 国际化Table1
      languageTable2: {}, // 国际化Table2
      languageData: {}, // 国际化语言包
      language: {},   // 国际化语言
      languageCode: JSON.parse(window.sessionStorage.userData).language, // 国际化语言标识
    }
    /*this.columns=[
         {
             title:"发票类型",
             dataIndex:'invTypeDesc',
             width:'100px',
             align:'center',
         },
         {
             title:"人员类型",
             dataIndex:'userTypeDesc',
             width:'100px',
             align:'center',
         },
         {
             title:'人员',
             dataIndex:'userName',
             width:'100px',
             align:'center'
 
         },
         {
             title:"生效日期",
             dataIndex:"startDate",
             width:'100px',
             align:'center'
         },
         {
             title:"失效日期",
             dataIndex:"stopDate",
             width:'100px',
             align:'center'
         },
         {
             title: '操作',
             dataIndex: 'operation',
             align: "center",
             width: '100Px',
             render: (text,record) => (
                 <span>
                     <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={this.handleDetele.bind(this, record)} >
                         <span className='span'>删除</span>
                     </Popconfirm>
                 </span>
             )
         },
         {
             title:"创建日期",
             dataIndex:"createDate",
             width:'100px',
             align:'center'
         },
         {
             title:"创建人",
             dataIndex:"createUserName",
             width:'100px',
             align:'center'
         }
         ,
         {
             title:"医院",
             dataIndex:"hospitalDesc",
             width:'100px',
             align:'center'
         }
     ]*/
  }






  //render 自定义项目名称
  listAdd = (i, j, languageCode) => {
    let { columns } = this.state
    columns.splice(i, j,
      {
        title: languageCode === 'CN' ? "操作" : 'Operation',
        key: 'op',
        width: '100px',
        align: "center",
        render: (text, record) => (
          <span>
            <Popconfirm
              title={languageCode === 'CN' ? "确定要删除吗?" : 'You sure you want to delete it?'}
              onConfirm={this.delConfirm}
              okText={languageCode === 'CN' ? "是" : 'Yes'}
              cancelText={languageCode === 'CN' ? "否" : 'No'}
              onConfirm={this.handleDetele.bind(this, record)}
            >
              <span style={{ color: '#f00' }} className='span'>{languageCode === 'CN' ? "删除" : 'Delete'}</span>
            </Popconfirm>
          </span>
        ),
      },
    )
  }
  onColumnRef = (ref) => {
    this.columnRef = ref;
  }
  // 获取主列表columns
  tableList = () => {
    var data = {
      params: [{
        "reactCode": ["PersonRelatedInvType"],
        "compontName": "PersonRelatedInvType",
        "type": "C"
      }]
    }
    $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();
    // 初始化列表数据
    let sessionInfo = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
    this.setState({ hospID: sessionInfo.hospID }, () => {
      this.tableList();
      //this.handleAuthor();
      this.handleQuery();
      this.handleInvTypeQuery();
      this.handleHospQuery();
      this.handleUserQuery();
    });

    // 初始化设置table的高度以及表体的高度
    //document.querySelector('.ant-table-body').style.height = store.getState().tableHeight.y + 'px';
    // 数据异步请求，请求成功之后setState
    this.setState({
      showLoading: false
    })
  }

  componentWillUnmount() {
    this.setState = (state, callback) => {
      return
    }
  }
  ///输入框值变化时需要绑定
  onChangeHospID = (value) => {
    this.setState({ hospID: value, userList: [] }, () => {
      this.handleAuthor();
      this.handleUserQuery();
    });
  }
  onChangeInvTypeID = (value) => {
    this.setState({
      invTypeID: value
    })
  }
  onChangeUserType = (value) => {
    this.setState({
      userType: value
    })
  }
  onChangeUserID = (value) => {
    this.setState({
      userID: value
    })
  }

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

  // 调用子组件的连接事件
  onRef = (ref) => {
    this.child = ref
  }
  //医院下拉框
  handleHospQuery = () => {
    let data = {}
    let sessionInfo = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
    data = {
      params: [{
        hospitalId: "",
        logonGroupID: sessionInfo.groupID,
        logonHospID: sessionInfo.hospID,
        hospRequired: "1",
      }]
    }
    $http.post('urlS', this, {
      code: '01040001',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0 && res.depDoctor) {
          let tempList = [];
          for (var i = 0; i < res.depDoctor.length; i++) {
            tempList.push(<Option key={res.depDoctor[i].id}>{res.depDoctor[i].descripts}</Option>)
          }
          this.setState({
            hospList: tempList
          })
        }
      }
    })
  }

  // 发票类型下拉框
  handleInvTypeQuery = () => {
    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
          })
        }
        /*else {
            setTimeout(() => {
                this.setState({ invList: [] })
            }, 1000)
        }*/
      }
    })
  }

  /*/ 人员下拉框
  handleUserQuery = () => {
      let {hospID} = this.state;
      let data = {}
      data = {
          params: [{
              hospID: hospID,
          }]
      }
      $http.post('urlS', this, {
          code: '05100027',
          data: data,
          success: function (res) {
              if (+res.errorCode === 0 && res.user) {
                  let tempList = this.state.userList
                  for (var i = 0; i < res.user.length; i++) {
                      tempList.push(<Option key={res.user[i].id} alias={res.user[i].descriptsSPCode}>{res.user[i].descripts}</Option>)
                  }
                  this.setState({
                      userList: tempList
                  })
              } 
          }
      })
  } 
  */
  // 页码改变的回调，参数是改变后的页码及每页条数
  appPageChange = (page, pageSize) => {
    this.setState({
      page: page,
      pageSize: pageSize,
    }, () => {
      // 重新调用查询方法
      this.handleQuery();
    });
  }

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



  // 为了返回第一页
  handleQueryBack = () => {
    this.setState({
      page: 1,
      pageSize: 10,
    }, () => {
      // 重新调用查询方法
      this.handleQuery();
    });

  }
  // 人员下拉框
  handleUserQuery = () => {
    let { hospID } = this.state;
    let data = {}
    data = {
      params: [{
        hospID: hospID,
        locTypeCode: "C",
      }]
    }
    $http.post('urlS', this, {
      code: '05210023',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0 && res.user) {
          let tempList = []
          for (var i = 0; i < res.user.length; i++) {
            tempList.push(<Option key={res.user[i].id} alias={res.user[i].descriptsSPCode}>{res.user[i].descripts}</Option>)
          }
          this.setState({
            userList: tempList,
            userData: res.user
          }
            , () => {
              let defaultSelect = this.state.userData.filter((item) => {
                return item.id === this.state.userID
              })
              if (defaultSelect.length < 1) {
                var chargeUserIDch = ""
                //if(this.state.userData.length>0){var chargeUserIDch=this.state.userData[0].id+""}else{var chargeUserIDch=""}
                this.setState({
                  userID: chargeUserIDch,
                })
              }
            }

          )
        }
      }
    })
  }



  // 人员下拉框
  handleAuthor = () => {
    let data = {}
    let sessionInfo = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
    data = {
      params: [{
        logonGroupID: sessionInfo.groupID,
        logonHospID: sessionInfo.hospID,
        hospRequired: "1",
      }]
    }
    $http.post('urlS', this, {
      code: '01040002',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          let addPower = (res.gridData.add && res.gridData.add.indexOf(hospID) > -1) || (res.gridData.add && res.gridData.add.indexOf('ALL') > -1) ? 1 : 0;
          let deletePower = (res.gridData.delete && res.gridData.delete.indexOf(hospID) > -1) || (res.gridData.find && res.gridData.delete.indexOf('ALL') > -1) ? 1 : 0;
          let updatePower = (res.gridData.update && res.gridData.update.indexOf(hospID) > -1) || (res.gridData.find && res.gridData.update.indexOf('ALL') > -1) ? 1 : 0;
          let findPower = (res.gridData.find && res.gridData.find.indexOf(hospID) > -1) || (res.gridData.find && res.gridData.find.indexOf('ALL') > -1) ? 1 : 0;
          console.log("findPower", findPower);
          this.setState({
            addPower: addPower,
            deletePower: deletePower,
            updatePower: updatePower,
            findPower: findPower,
          })

        }
      }
    })
  }








  // 查询数据
  handleQuery = () => {
    let { addPower, deletePower, updatePower, findPower } = this.state;
    if (findPower === 1) {
      let { userType, hospID, invTypeID, userID, page, pageSize } = this.state;
      let data = {}
      if (userType || invTypeID) {
        data = {
          params: [{
            userType: userType,
            invTypeID: invTypeID,
            hospID: hospID,
            userID: userID
          }],
          pagination: [{
            pageSize: 10,
            currentPage: 1,
            sortColumn: "Code",
            sortOrder: "asc"
          }]
        }
      } else {
        data = {
          params: [{
            userType: userType,
            invTypeID: invTypeID,
            hospID: hospID,
            userID: userID
          }],
          pagination: [{
            pageSize: pageSize,
            currentPage: page,
            sortColumn: "Code",
            sortOrder: "asc"
          }]
        }
      }
      $http.post('urlS', this, {
        code: '05100037',
        data: data,
        success: function (res) {
          if (+res.errorCode === 0 && res.invInfo) {
            for (var i = 0; i < res.invInfo.length; i++) {
              res.invInfo[i].key = i;
            }
            this.setState({ data: res.invInfo, total: res.total, loading: false })
          }

        }
      })
    } else {
      console.log("进入次数");
      message.error("没有查询权限");
      this.setState({ data: [], total: 0, loading: true })
    }
  }

  //增加方法
  handleAdd = () => {
    let { addPower, deletePower, updatePower, findPower } = this.state;
    if (addPower === 1) {
      // 显示弹框
      this.child.showModal()
      // 初始化数据
      this.setState({ flag: 'add', title: '新增' })
    } else {
      message.error("没有新增权限");
    }
  }
  //修改方法
  handleCompile(record) {
    let { addPower, deletePower, updatePower, findPower } = this.state;
    if (updatePower === 1) {
      // 重置form表单
      this.child.resetFields()
      // 打开弹框
      this.child.showModal();
      // 初始化数据
      this.setState({ flag: 'compile', userInfo: record, title: '编辑' });
    } else {
      message.error("没有修改权限");
    }
  }
  // 删除
  handleDetele(record) {
    let { addPower, deletePower, updatePower, findPower } = this.state;
    if (updatePower === 1) {
      //获取sessionStorage的数据
      let sessionInfo = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
      let updateUserID = sessionInfo.userID;
      let data = {
        params: [{
          invTypeConUserTypeID: record.invTypeConUserTypeID,
          invTypeConUserID: record.invTypeConUserID,
          updateUserID: updateUserID
        }]
      }
      $http.post('urlADS', this, {
        code: '05100040',
        data: data,
        success: function (res) {
          if (+res.errorCode === 0) {
            message.success('删除成功');
            // 刷新列表数据
            this.handleQuery()
          } else {
            message.error('删除失败：' + res.errorMessage);
          }
        },
        error: function (error) {
          message.error('删除失败：' + error);
        }
      })
    } else {
      message.error('没有删除权限');
    }
  }

  //渲染 
  render() {
    let { language } = this.state
    return (

      <div>
        < div className="table-operations" style={{ minHeight: '50px', padding: '0 24px 10px 24px' }} >
          {language.PersonRelatedInvTypeyy && language.PersonRelatedInvTypeyy.descripts}：<Select
            showSearch
            allowClear
            placeholder="请输入"
            optionFilterProp="children"
            style={{ width: "150px", margin: '12px 15px 0 0' }}
            value={this.state.hospID}
            onChange={this.onChangeHospID}
            filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
          >{this.state.hospList}</Select>
          {language.PersonRelatedInvTypefplx && language.PersonRelatedInvTypefplx.descripts}：<Select
            showSearch
            allowClear={true}
            placeholder="请输入"
            optionFilterProp="children"
            onChange={this.onChangeInvTypeID}
            value={this.state.invTypeID}
            style={{ width: '150px', margin: '12px 15px 0 0' }}
            filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
          >{this.state.invList}</Select>
          {language.PersonRelatedInvTyperylx && language.PersonRelatedInvTyperylx.descripts}：<Select
            showSearch
            allowClear={true}
            placeholder="请输入"
            optionFilterProp="children"
            style={{ width: '150px', margin: '12px 15px 0 0' }}
            value={this.state.userType}
            onChange={this.onChangeUserType}
            filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
          >
            <Option value="1">管理员</Option>
            <Option value="2">票据购入员</Option>
            <Option value="3">收费员</Option>
          </Select>
          {language.PersonRelatedInvTypery && language.PersonRelatedInvTypery.descripts}：<Select
            showSearch
            allowClear={true}
            placeholder="请输入"
            optionFilterProp="children"
            style={{ width: '150px', margin: '12px 15px 0 0' }}
            value={this.state.userID}
            onChange={this.onChangeUserID}
            filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
          >{this.state.userList}</Select>
          <Button type="primary" onClick={this.handleQueryBack} style={{ margin: '12px 15px 0 0' }}> {language.PersonRelatedInvTypecx && language.PersonRelatedInvTypecx.descripts}</Button>
          <Button type="primary" onClick={this.handleAdd} style={{ margin: '12px 15px 0 0' }}> {language.PersonRelatedInvTypexzryfpqx && language.PersonRelatedInvTypexzryfpqx.descripts}</Button>


        </div>
        <div style={{ background: '#f0f2f5', height: '10px' }}></div>
        <div style={{ padding: 24 }}>
          <Table
            style={{ height: store.getState().tableHeight.y + 65 + 'px' }}
            dataSource={this.state.data}
            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.data}
            onChange={this.appPageChange} />
          <ColumnAuthoritysModel
            clientWidth='900px'
            compontName='PersonRelatedInvType'
            configType="C"
            onRef={this.onColumnRef}
            reloadData={this.tableList}
          />
          <PersonRelatedInvTypeModal
            onRef={this.onRef}
            userInfo={this.state.userInfo}
            flag={this.state.flag}
            handelThis={this}
            title={this.state.title}
          />
        </div>
      </div>
    )
  }


}