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

export default class TarTypeMenu extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      code: '',
      desc: '',
      userInfo: {},
      // 主菜单列表数据
      data: [],
      // 抽屉显示
      visible: false,
      // 主菜单分页数据
      total: 0,
      page: 1,
      pageSize: 10,
      flag: '',
      title: '',
      // 是否显示loading
      showLoading: true,
      // 表格loading
      loading: true,
      hospID: '',
      hospList: [],
      languageTable1: {}, // 国际化Table1
      languageTable2: {}, // 国际化Table2
      languageData: {}, // 国际化语言包
      language: {},   // 国际化语言
      languageCode: JSON.parse(window.sessionStorage.userData).language, // 国际化语言标识
    }
    /*this.columns = [
      {
        title: "类型",
        dataIndex: "typeDesc",
        width: '100px',
        align: 'center'
      },
      {
        title: "大类代码",
        dataIndex: 'code',
        width: '100px',
        align: 'center',
      },
      {
        title: '大类名称',
        dataIndex: 'descripts',
        width: '100px',
        align: 'center'

      },
      {
        title: "医院",
        dataIndex: 'hospName',
        width: '100px',
        align: 'center',


      },
      {
        title: "创建日期",
        dataIndex: "createDate",
        width: '100px',
        align: 'center'
      },
      {
        title: "创建人",
        dataIndex: "createUserName",
        width: '100px',
        align: 'center'
      },
      {
        title: "操作",
        dataIndex: "caozuo",
        width: '100px',
        align: 'center'
      }
    ]*/
  }



  componentDidMount() {
    this.tableList();
    // 初始化列表数据
    let sessionInfo = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
    this.setState({ hospID: sessionInfo.hospID }, () => {
      this.handleQuery();
      this.handleHospQuery();
    });

    // 初始化设置table的高度以及表体的高度
    document.querySelector('.ant-table-body').style.height = store.getState().tableHeight.y + 'px';
    // 数据异步请求，请求成功之后setState
    this.setState({
      showLoading: false
    })
  }
  componentWillUnmount() {
    this.setState = (state, callback) => {
      return
    }
  }
  /*componentWillUnmount() {
     this.setState = (state,callback)=>{ return; }; 
     // 组件销毁前清除监听
     //window.removeEventListener('resize', this.handelHeight);
 }*/

  // 获取主列表columns
  tableList = () => {
    var data = {
      params: [{
        "reactCode": ["TarTypeMenu"],
        "compontName": "TarTypeMenu",
        "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]
    })
  }

  //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>
            <span className='span' onClick={this.handleCompile.bind(this, record)}>{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'}
              onConfirm={this.handleDetele.bind(this, record)}
            >
              <span style={{ color: '#f00' }} className='span'>{languageCode === 'CN' ? "删除" : 'Delete'}</span>
            </Popconfirm>
          </span>
        ),
      },
    )
  }


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

  onColumnRef = (ref) => {
    this.columnRef = ref;
  }

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

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


  /***下拉框***/
  //医院下拉框
  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
          })
        }
      }
    })
  }





  /***双向绑定***/
  onChangeCode = (e) => {
    this.setState({
      code: e.target.value
    })

  }
  onChangeDesc = (e) => {
    this.setState({
      desc: e.target.value
    });
  }
  onChangeHospID = (value) => {
    this.setState({
      hospID: value
    });
  }



  /***增删改查***/
  // 查询
  handleQuery = () => {
    let { code, desc, page, pageSize, hospID } = this.state;
    let sessionInfo = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
    let data = {}
    if (code || desc) {
      data = {
        params: [{
          code: code,
          descripts: desc,
          hospID: hospID
        }],
        pagination: [{
          pageSize: 10,
          currentPage: 1,
          sortColumn: "Code",
          sortOrder: "asc"
        }]
      }
    } else {
      data = {
        params: [{
          code: code,
          descripts: desc,
          hospID: hospID
        }],
        pagination: [{
          pageSize: pageSize,
          currentPage: page,
          sortColumn: "Code",
          sortOrder: "asc"
        }]
      }
    }
    $http.post('urlS', this, {
      code: '05100014',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0 && res.tarType) {
          for (var i = 0; i < res.tarType.length; i++) {
            res.tarType[i].key = i;
          }
          this.setState({ data: res.tarType, total: res.total, loading: false })
        }
        /*else {
            setTimeout(() => {
                this.setState({data: [], total: 0, loading: false})
            }, 3000)
        }*/
      }
    })
  }
  //增加方法
  handleAdd = () => {
    // 显示弹框
    this.child.showModal()
    // 初始化数据
    this.setState({ flag: 'add', title: '新增' })
  }
  //修改方法
  handleCompile(record) {
    // 重置form表单
    this.child.resetFields()
    // 打开弹框
    this.child.showModal();
    // 初始化数据
    this.setState({ flag: 'compile', userInfo: record, title: '编辑' });
  }
  // 删除
  handleDetele(record) {
    let sessionInfo = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
    let data = {
      params: [{
        tarTypeID: record.tarTypeID,
        updateUserID: sessionInfo.userID
      }]
    }
    $http.post('urlADS', this, {
      code: '05100017',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          message.success('删除成功');
          // 刷新列表数据
          this.handleQuery()
        }
      },
      error: function (error) {
        message.error('删除失败：' + error);
      }
    })
  }



  render() {
    let { language } = this.state
    return (
      <div>
        < div >
          {/*写成标签对可以但不要分离太远*/}
          <p>{language.TarTypeMenuqutry && language.TarTypeMenuqutry.descripts}：</p>
          {language.TarTypeMenusfdldm && language.TarTypeMenusfdldm.descripts}： <Input placeholder="请输入代码" style={{ width: '150px' }} value={this.state.code} onChange={this.onChangeCode} />
          {language.TarTypeMenusfdlms && language.TarTypeMenusfdlms.descripts}： <Input placeholder='请输入描述' style={{ width: "150px" }} value={this.state.desc} onChange={this.onChangeDesc} />
          {language.TarTypeMenuyy && language.TarTypeMenuyy.descripts}： <Select
            showSearch
            allowClear
            placeholder="请输入"
            optionFilterProp="children"
            style={{ width: "150px" }}
            value={this.state.hospID}
            onChange={this.onChangeHospID}
            filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
          >{this.state.hospList}</Select>
          <Button type="primary" onClick={this.handleQuery} style={{ marginLeft: '30px' }}>{language.TarTypeMenucx && language.TarTypeMenucx.descripts}</Button>
          <Button type="primary" onClick={this.handleAdd} style={{ marginLeft: '30px' }}>{language.TarTypeMenuxz && language.TarTypeMenuxz.descripts}</Button>
          <Table
            style={{ height: store.getState().tableHeight.y + 65 + 'px' }}
            dataSource={this.state.data}
            columns={this.state.columns}
            className='TableA'
            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='TarTypeMenu'
            configType="C"
            onRef={this.onColumnRef}
            reloadData={this.tableList}
          />
        </div>
        <TarTypeModal
          onRef={this.onRef}
          userInfo={this.state.userInfo}
          flag={this.state.flag}
          handelThis={this}
          title={this.state.title}
        />
      </div>
    )
  }
}