/*
 * Creater:     shizi
 * CreateDate:  2022/03/31
 * Describe：   新药品信息
 * */
import React, { Component } from 'react';
import { Row, Col, Card, Input, Select, Button, Divider, Popconfirm, message } from 'antd';
import store from 'store';
import { Util } from 'tools';

import PubilcTablePagination from 'pages/common/PubilcTablePagination.jsx';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import AddDrugs from './newDrugComponent/AddDrugs';
import iconListvisits from 'assets/images/icon_listvisits.png';
import './style/new-drug.less';

class NewDrugInformation extends Component {
  constructor(props) {
    super(props);
    var userData = JSON.parse(sessionStorage.getItem('userData'));
    this.state = {
      userData,
      selectData: {}, // 下拉数据
      category: '', // 类别
      medAlias: undefined, // 代码
      stkCatID: undefined, // 库存大类
      statusID: undefined, // 状态
      columns: [], // 表头数据
      tableData: [],
      total: 0,
      page: 1,
      pageSize: 20,
      totalwidth: 420,
      loading: false,
      rowID: ''
    };
  }

  componentDidMount() {
    let category;
    if ('paras' in this.props && this.props.paras.type) { // 侧菜单获取类别参数
      category = this.props.paras.type;
    } else {
      if ('location' in this.props && this.props.location.state && this.props.location.state.type) { // 头菜单获取类别参数
        category = this.props.location.state.type;
        React.$setSessionData('drugCategory', category, false);
      } else { // 头菜单刷新界面时获取类别
        category = React.$getSessionData('drugCategory', false);
      }
    }
    this.setState({ category, loading: true, statusID: 'U' }, () => {
      this.getTableColumns();
      this.getSelectData();
      this.handleQuery();
    })
  }

  // 获取下拉列表数据
  getSelectData = async () => {
    let selectData = await React.$asyncPost(this, '02020382');
    this.setState({ selectData })
  }

  // 获取列表columns
  getTableColumns = async () => {
    let { userData } = this.state;
    let columsOperation = {
      title: '操作',
      dataIndex: 'operation',
      fixed: 'right',
      align: "center",
      width: 130,
      render: (text, record) => (
        <span>
          {'deleteFlag' in record && record.deleteFlag === 'Y' ? (
            <Popconfirm title="删除不可恢复，你确定要删除吗?" onCancel={this.handlePopconfirm} onClick={this.handlePopconfirm} onConfirm={(e) => this.handleDelete(record, e)} >
              <span className='span' style={{ color: 'rgba(240,65,52,1)' }}>删除</span>
            </Popconfirm>
          ) : (
            <span className='span' style={{ color: '#999' }} onClick={this.handlePopconfirm}>删除</span>
          )}
          {/* 分割线 */}
          <Divider type="vertical" />
          <span className='span' onClick={(e) => this.handleCopy(e, record)}>另存</span>
        </span>
      ),
    }
    try {
      let data = {
        params: [{
          compontName: "NewDrugInformation",
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let arr = res.result.C && res.result.C.length > 0 ? JSON.parse(JSON.stringify(res.result.C)).map((item, index) => {
        return {
          ...item,
          key: index + 1,
          title: <div onDoubleClick={() => this.columnRef.onOpenModel()}>{userData.language == 'EN' ? (item && item.enDescripts ? item.enDescripts : item.title) : item.title}</div>
        }
      }) : '';
      let filterArr = arr.filter(function (item) { return item.display === 'Y' });
      filterArr.push(columsOperation);
      this.setState({
        columns: filterArr,
        widthTotal: res.totalWidth
      })
    } catch (error) {
      let staticColumns = [{
        key: 1,
        title: '代码',
        dataIndex: 'medCode',
        align: 'center'
      }, {
        key: 2,
        title: '名称',
        dataIndex: 'medDesc',
        align: 'center'
      }]
      staticColumns.push(columsOperation);
      this.setState({ columns: staticColumns })
    }
  }

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

  // 查询
  handleQuery = () => {
    this.setState({ page: 1, rowID: '' }, () => {
      this.getTableData();
      this.handleResetFields();
    })
  }

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

  // 请求列表数据
  getTableData = async (id) => {
    this.setState({ loading: true })
    try {
      let { medAlias, stkCatID, statusID, pageSize, page } = this.state;
      let data = {
        params: [{
          medAlias,
          stkCatID,
          statusID
        }],
        pagination: [{
          pageSize,
          currentPage: page
        }]
      }
      let res = await React.$asyncPost(this, '02020377', data);
      let tableData = res.result && 'rows' in res.result ? Util.addKeyValueToDataSource(res.result.rows) : [];
      this.setState({ tableData, total: res.result.total, loading: false }, () => {
        // if (id) { // 新增或编辑时列表不存在这条数据则清空操作
        //   let isReset = true;
        //   for (var i = 0; i < this.state.tableData.length; i++) {
        //     if (String(this.state.tableData[i].medID) === String(id)) {
        //       isReset = false;
        //       break;
        //     }
        //   }
        //   if (isReset && this.state.rowID) { // 重置
        //     this.handleAdd();
        //   } else {
        //     this.setState({ rowID: id }, () => {
        //       this.queryRowDataByID();
        //     }) // 选中行
        //   }
        // }
        id ? this.setState({ rowID: id }, () => {
          this.queryRowDataByID();
        }) : ''; // 选中行
      });
    } catch (error) {
      this.setState({ tableData: [], total: 0, loading: false })
    }
  }

  // 点击删除时阻止事件冒泡
  handlePopconfirm = (e) => {
    e.stopPropagation();
  };

  // 删除
  handleDelete = async (record, e) => {
    e && e.stopPropagation && e.stopPropagation();
    try {
      let { rowID } = this.state;
      let data = {
        params: [{
          hospMedID: record.hospMedID
        }],
      }
      let res = await React.$asyncPost(this, '02020381', data);
      message.success(res && res.errorMessage ? res.errorMessage : '删除成功')
      if (rowID === record.medID) {
        this.handleAdd();
        this.getTableData();
      } else { // 重新查询
        this.getTableData();
      }
    } catch (error) {
      console.log(error);
    }
  }

  // 另存
  handleCopy = (e, record) => {
    e.stopPropagation && e.stopPropagation();
    this.setState({ rowID: '' }, () => {
      this.durgsChild && this.durgsChild.queryRowDataByID(record.medID, true);
    });
  }

  // 保存
  handleSave = () => {
    this.durgsChild && this.durgsChild.handleSave();
  }

  // 新增医嘱项
  handleAdd = () => {
    this.setState({ rowID: '' });
    this.handleResetFields();
  }

  // 重置
  handleResetFields = () => {
    this.durgsChild && this.durgsChild.resetFields();
  }

  // 操作行
  onClickRowPublic = (record) => {
    return {
      // 单击行选中
      onClick: () => {
        if (this.state.rowID === '') {
          this.setState({ rowID: record.medID }, () => {
            this.queryRowDataByID();
          })
        } else {
          if (this.state.rowID !== record.medID) {
            this.setState({ rowID: record.medID }, () => {
              this.queryRowDataByID();
            })
          } else {
            this.setState({ rowID: '' }, () => {
              this.handleResetFields();
            })
          }
        }
      }
    }
  }

  // 选中行操作
  setRowClassNamePublic = (record) => {
    return record.medID === this.state.rowID ? 'clickRowStyle' : "";
  }

  // 根据ID查询行数据
  queryRowDataByID = () => {
    let { rowID } = this.state;
    this.durgsChild && this.durgsChild.queryRowDataByID(rowID);
  }

  render() {
    let { medAlias, stkCatID, statusID, columns, tableData, totalwidth, total, page, loading, selectData, rowID } = this.state;

    // 组件所需参数
    const param = {
      componentName: 'NewDrugInformation',
      // 表头配置
      columns: columns,
      // 表格数据
      data: tableData,
      // 数据总条数
      total,
      // 当前页数
      page,
      pageSize: '20',
      loading,
      // 表格的宽度
      x: totalwidth,
      y: store.getState().tableHeight.y + 108 - 102,
      height: store.getState().tableHeight.y + 158 - 102 + 'px',
      isOnRow: true,
      rowClassName: true,
    }
    return (
      <div className='new-drug-information'>
        <Row className='ndi-header'>
          <Col span={16}>
            代码/描述：<Input
              title="输入内容后可回车检索"
              placeholder="请输入检索条件"
              value={medAlias}
              onChange={Util.commonInputChange.bind(this, 'medAlias')}
              onPressEnter={this.handleQuery}
              style={{ width: '200px', marginRight: '12px' }}
            />
            库存大类：<Select
              allowClear
              showSearch
              optionFilterProp="seachprop"
              placeholder="请选择"
              value={stkCatID}
              onChange={Util.handleSelectChange.bind(this, 'stkCatID')}
              style={{ width: '200px', marginRight: '12px' }}
            >
              {selectData && selectData.stkCat ? React.$SelectOptions(selectData.stkCat) : ''}
            </Select>
            状态：<Select
              allowClear
              showSearch
              optionFilterProp="seachprop"
              placeholder="状态"
              value={statusID}
              onChange={Util.handleSelectChange.bind(this, 'statusID')}
              style={{ width: '200px', marginRight: '20px' }}
            >
              {selectData && selectData.status ? React.$SelectOptions(selectData.status) : ''}
            </Select>
            <Button type="primary" onClick={this.handleQuery}>查询</Button>
          </Col>
          <Col span={8} className='ndi-header-right'>
            {/* <Button type="primary" ghost>下载导入模板</Button>
            <Button type="primary" icon="download" ghost>导入</Button>
            <Button type="primary" icon="download" ghost>导出</Button>
            <Button style={{ background: 'rgba(247,128,93,1)', color: '#fff' }}>其他医院复制</Button> */}
          </Col>
        </Row>
        <div style={{ widht: '100%', height: '10px', background: '#f0f2f5' }}></div>
        <Row className='ndi-content'>
          <Col span={8}>
            <div
              tabIndex={1}
              onKeyDown={this.handleOnKeydown}
              style={{ outline: 'none', paddingRight: '6px', position: 'relative', height: '100%' }}
            >
              <Card
                size="small"
                className="table-body-height"
                title={<div className="card-title-left-img ndir-card-heade">
                  <div>
                    <img src={iconListvisits} alt="" />药品列表
                  </div>
                  <div>
                    <Button style={{ display: 'none' }} type="primary" ghost>从公共字典选择</Button>
                  </div>
                </div>}
              >
                {/* handelThis将夫组件的属性与方法给子组件访问 */}
                <PubilcTablePagination
                  param={param}
                  compilePage={this.compilePage}
                  onClickRowPublic={this.onClickRowPublic}
                  setRowClassNamePublic={this.setRowClassNamePublic}
                />
              </Card>
              <div style={{ width: '6px', background: 'rgba(240, 242, 245, 1)', position: 'absolute', top: 0, right: 0, height: '100%' }}></div>
            </div>
          </Col>
          <Col span={16}>
            <Card
              size="small"
              title={<div className='card-title-left-img ndir-card-heade'>
                <div>
                  <img src={iconListvisits} alt="" />
                  <span style={{ fontWeight: 'bold', color: '#1890ff' }}>正在{rowID ? '修改' : '添加'}药品……</span>
                </div>
                {rowID ? <Button type="primary" icon='plus' onClick={this.handleAdd}>新增药品</Button> : ''}
              </div>}
              style={{ height: store.getState().tableHeight.y + 168 + 'px' }}
            >
              <AddDrugs
                height={store.getState().tableHeight.y + 40}
                selectData={selectData}
                getTableData={this.getTableData}
                resetFields={this.handleAdd}
                onRef={ref => this.durgsChild = ref}
              />
              <div className='ndi-content-footer'>
                {rowID ? (
                  <Popconfirm title="取消修改会导致表单清空，你确定要取消吗?" onConfirm={this.handleAdd} >
                    <Button className='ndi-btn-margin'>取消修改</Button>
                  </Popconfirm>
                ) : (
                  <Button className='ndi-btn-margin' onClick={this.handleResetFields}>清空</Button>
                )}
                <Button type="primary" onClick={this.handleSave}>{rowID ? '确认修改' : '保存'}</Button>
              </div>
            </Card>
          </Col>
        </Row>
        {/* 更改表头配置 */}
        <ColumnAuthoritysModel
          clientWidth='800px'
          compontName='NewDrugInformation'
          configType="C"
          onRef={this.handleColumnRef}
          reloadData={this.getTableColumns}
        />
      </div>
    );
  }
}

export default NewDrugInformation;