/*
 * Create:      柿子
 * CreateDate:  2022/10/31
 * Describe：   手术医保
 * */
import React, { Component } from 'react';
import { Card, Row, Col, Input, Select, Button, DatePicker, message, Icon, Divider, Popconfirm, Tooltip } from 'antd';
import { Util, dayFormat } from 'tools';
import store from 'store';
import moment from 'moment';
import PubilcTablePagination from 'pages/common/PubilcTablePagination.jsx';
import PublicModalFormHooks from 'pages/common/PublicModalFormHooks';
import iconListvisits from 'assets/images/icon_listvisits.png';

class MedicalInsuranceOperation extends Component {
  constructor(props) {
    super(props);
    let userData = React.$getSessionData();
    this.state = {
      userData,
      queryParams: { // 查询条件
        diagnosisDesc: undefined,
        insuTypeID: undefined,
        startDate: moment(),
        endDate: undefined,
      },
      loading: false,
      page: 1,
      pageSize: 20,
      tableData: [],
      total: 0,
      selectData: [],
      rowID: '',
      rowData: {},
      formData: [],
      columns: [],
      totalWidth: 1240
    };

    this.columns = [{
      title: '医保类型',
      dataIndex: 'typeDesc',
      width: 120,
      align: 'center'
    }, {
      title: '诊断代码',
      dataIndex: 'code',
      width: 120,
      align: 'center'
    }, {
      title: '诊断内容',
      dataIndex: 'descripts',
      width: 220,
      align: 'center'
    }, {
      title: 'ICD10诊断代码',
      dataIndex: 'ICDCode',
      width: 120,
      align: 'center'
    }, {
      title: 'ICD10诊断描述',
      dataIndex: 'ICDDesc',
      width: 120,
      align: 'center'
    }, {
      title: '生效日期',
      dataIndex: 'startDate',
      width: 120,
      align: 'center'
    }, {
      title: '失效日期',
      dataIndex: 'stopDate',
      width: 120,
      align: 'center'
    }]
  }

  componentDidMount() {
    this.getSelectData();
    this.handleQuery();
    this.getFormData();
    this.getColumnsData();
  }

  // 获取下拉数据
  getSelectData = async () => {
    try {
      let { userData } = this.state;
      let data = {
        params: [{
          hospID: userData?.hospID || ''
        }]
      }
      let res = await React.$asyncPost(this, '05100389', data);
      this.setState({ selectData: res });
    } catch (error) {
      this.setState({ selectData: [] });
    }
  }

  // 获取订单列表表头数据
  getColumnsData = async () => {
    try {
      let data = {
        params: [{
          type: 'C',
          compontName: 'MedicalInsuranceOperation',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let columns = res.result && res.result.C && res.result.C.length > 0 ? res.result.C : [];
      if (columns && columns.length > 0) {
        columns = columns.map(item => {
          return {
            ...item,
            render: (text, record) => {
              return (
                <Tooltip title={text}>
                  <span className='ellipsis' style={{ width: '100%', display: 'block' }}>{text}</span>
                </Tooltip>
              );
            },
          }
        })
        this.setState({
          columns: columns,
          totalWidth: res.totalWidth
        })
      }
    } catch (error) {
      console.log(error)
    }
  }

  // 获取操作数据
  getFormData = () => {
    let formData = [{
      dataIndex: 'code',
      title: '代码',
      typeCode: 'Input',
      required: 'Y',
    }, {
      dataIndex: 'desc',
      title: '描述',
      typeCode: 'Input',
      required: 'Y',
    }];
    this.setState({ formData });
  }

  // 修改操作框数据
  handleModifyInputValue = (e, dataIndex) => {
    this.state.queryParams[dataIndex] = e;
    this.setState({});
  }

  // 查询
  handleQuery = () => {
    this.setState({ page: 1, loading: true }, () => {
      this.getTableData();
    })
  }

  // 删除
  handleDelete = async (record) => {
    try {
      this.handleStopPropagation(e);
      const { rowID, userData } = this.state;
      let data = {
        params: [{
          proKID: record.ID,
          updateUserID: userData.userID
        }]
      }
      let res = await React.$asyncPost(this, '17030013', data);
      message.success(res.errorMessage || '删除成功');
      this.getTableData(rowID === record.ID ? 'Y' : 'N');
    } catch (error) {
      console.log(error)
    }
  }

  // 添加
  handleAdd = () => {
    let { rowData } = this.state;
    if (rowData && 'ID' in rowData && rowData.ID) {
      this.setState({ rowData: {} })
    }
    this.modalFormRef && this.modalFormRef.modifyVisible(true);
  }

  // 编辑
  handleCompile = (record, e) => {
    this.handleStopPropagation(e);
    this.setState({ rowData: record }, () => {
      this.modalFormRef && this.modalFormRef.modifyVisible(true);
    })
  }

  // 分页操作
  compilePage = (page, pageSize) => {
    this.setState({ page, pageSize }, () => {
      this.getTableData();
    })
  }

  // 获取列表数据
  getTableData = async () => {
    try {
      let { queryParams, page, pageSize } = this.state;
      var data = {
        params: [{
          ...queryParams,
          endDate: queryParams.endDate ? moment(queryParams.endDate).format(dayFormat) : '',
          startDate: queryParams.startDate ? moment(queryParams.startDate).format(dayFormat) : '',
        }],
        pagination: [{
          pageSize,
          currentPage: page
        }]
      }
      let res = await React.$asyncPost(this, '05100409', data);
      let tableData = res.result && 'rows' in res.result ? Util.addKeyValueToDataSource(res.result.rows) : [];
      this.setState({ tableData, total: res.result.total, loading: false, rowID: '' });
    } catch (error) {
      this.setState({ tableData: [], total: 0, loading: false, rowID: '' });
    }
  }

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

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

  // 点击input框时阻止事件冒泡
  handleStopPropagation = (e) => {
    e.stopPropagation();
  }

  // 保存
  handleSave = async values => {
    try {
      let { rowID } = this.state;
      let data = {
        params: [{
          ...values,
          ID: rowID
        }]
      }
      let res = await React.$asyncPost(this, '123', data);
      message.success(res?.errorMessage || '保存成功');
      this.modalFormRef && this.modalFormRef.modifyVisible(false, 'Y');
      this.setState({ rowData: {} }, () => {
        this.getTableData();
      });
    } catch (error) {
      console.log(error)
    }
  }

  // 记录表单的值
  recordFormInput = record => {
    this.setState({ rowData: { ...this.state.rowData, ...record } })
  }

  render() {
    let { queryParams, tableData, page, total, loading, selectData, formData, rowData, columns, totalWidth } = this.state;
    /*
    let opertionObj = {
      title: '操作',
      align: 'center',
      width: 100,
      fixed: 'right',
      render: (text, record) => (
        <span>
          <Icon type="edit" style={{ color: '#108EE9' }}></Icon>
          <span className='span' onClick={(e) => this.handleCompile(record, e)}>编辑</span>
          <Divider type="vertical"></Divider>
          <Icon type="delete" className="common-record-delete-span"></Icon>
          <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={(e) => this.handleDelete(record, e)} >
            <span className="span common-record-delete-span">删除</span>
          </Popconfirm>
        </span>
      ),
    }
    */
    return (
      <div className="medical-insurance-operation">
        <Row className="common-query-header">
          <Col span={20}>
            诊断名称：
            <Input
              allowClear
              placeholder="请输入"
              className="common-query-input"
              value={queryParams.diagnosisDesc}
              onChange={(e) => this.handleModifyInputValue(e.target.value, 'diagnosisDesc')}
              onPressEnter={this.handleQuery}
            />
            医保类型：
            <Select
              allowClear
              placeholder="请选择"
              optionFilterProp="search"
              className="common-query-input"
              value={queryParams.insuTypeID}
              onChange={(e) => this.handleModifyInputValue(e, 'insuTypeID')}
            >
              {React.$SelectOptions(selectData?.medicalType || [])}
            </Select>
            生效日期：<DatePicker
              allowClear
              value={queryParams.startDate}
              placeholder="请选择生效日期"
              className="common-query-input"
              onChange={(e) => this.handleModifyInputValue(e, 'startDate')}
            />
            失效日期：<DatePicker
              allowClear
              value={queryParams.endDate}
              placeholder="请选择失效日期"
              className="common-query-input"
              onChange={(e) => this.handleModifyInputValue(e, 'endDate')}
            />
            <Button style={{ marginTop: '8px' }} onClick={this.handleQuery}>查询</Button>
          </Col>
          <Col span={4} style={{ textAlign: 'right' }}>
            {/* <Button
              icon="plus"
              className="add-btn add-btn-nohover"
              onClick={this.handleAdd}
            >
              新增
            </Button> */}
          </Col>
        </Row>
        <div className="common-query-split-line" style={{ height: 8 }}></div>
        <Card
          size="small"
          bordered={false}
          title={(
            <div className="card-title-left-img">
              <img src={iconListvisits} alt="" />
              手术列表
            </div>
          )}
        >
          <div className="table-body-height">
            <PubilcTablePagination
              param={{
                page,
                total,
                loading,
                pageSize: 20,
                data: tableData, // 表格数据
                x: totalWidth, // 表格的宽度
                y: store.getState().tableHeight.y - 15,
                componentName: 'MedicalInsuranceOperation',
                height: store.getState().tableHeight.y + 35 + 'px',
                columns: columns && columns.length > 0 ? [...columns] : [...this.columns], // 表头配置
              }}
              compilePage={this.compilePage}
              getColumns={this.getTableColumns}
              onClickRowPublic={this.onClickRowPublic}
              setRowClassNamePublic={this.setRowClassNamePublic}
            />
          </div>
        </Card>

        <PublicModalFormHooks
          idField='ID'
          title="手术医保"
          rowData={rowData}
          formData={formData}
          formItemCol={{ labelCol: 5, wrapperCol: 16, col: 24 }}
          onRef={ref => this.modalFormRef = ref}
          recordFormInput={this.recordFormInput}
          handleSave={this.handleSave}
        />
      </div>
    );
  }
}

export default MedicalInsuranceOperation;
