/*
 * Creater:     shizi
 * CreateDate:  2022/04/27
 * Describe：   医院组维护 -> 左右形式增删改查示例
 * */
import React, { Component } from 'react';
import { Row, Col, Input, Select, Button, Card, message, Popconfirm, Divider, Icon } from 'antd';
import store from 'store';
import { Util } from 'tools';
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 HospitalGroupMaintenance extends Component {
  constructor(props) {
    super(props);
    this.state = {
      desc: undefined, // 模糊搜索条件
      status: undefined,
      mainTableData: [],
      mainFormData: [], // 主表表单数据
      mainTotal: 0,
      mainPage: 1,
      mainPageSize: 20,
      mainLoading: false,
      rowID: '',
      rowData: {},
      detailTableData: [],
      detailFormData: [], // 明细表单数据
      detailTotal: 0,
      detailPage: 1,
      detailPageSize: 20,
      detailLoading: false,
      detailRowData: {},
      hospArr: [],
      statusArr: [],
      reAdmTypeArr: []
    };
    // 主表表头数据
    this.mainColumns = [{
      key: 1,
      title: '代码',
      dataIndex: 'code',
      align: "center",
      width: "100px"
    }, {
      key: 2,
      title: '名称',
      dataIndex: 'descripts',
      align: "center",
      width: "100px"
    }, {
      key: 3,
      title: '英文描述',
      dataIndex: 'eNDesc',
      align: "center",
      width: "100px"
    }, {
      key: 4,
      title: '复诊类型',
      dataIndex: 'reAdmTypeDesc',
      align: "center",
      width: "100px"
    },
    {
      key: 5,
      title: '初诊有效期(天)(综合计算起作用)',
      dataIndex: 'regReAdmDate',
      align: "center",
      width: "200px"
    },
    {
      key: 6,
      title: '不同医生(科室)算做初诊(综合计算起作用)',
      dataIndex: 'regReDoctorFlag',
      align: "center",
      width: "200px"
    }, {
      key: 7,
      title: '生效时间',
      dataIndex: 'startDate',
      align: "center",
      width: "100px"
    }, {
      key: 8,
      title: '失效时间',
      dataIndex: 'stopDate',
      align: "center",
      width: "100px"
    }];
    // 明细表头数据
    this.detailColumns = [{
      key: 1,
      title: '医院',
      dataIndex: 'hospDesc',
      align: "center"
    }, {
      key: 2,
      title: '级别',
      dataIndex: 'level',
      align: "center",
      width: "150px"
    }, {
      key: 3,
      title: '初诊有效期(天)(单独计算起作用)',
      dataIndex: 'regReAdmDate',
      align: "center",
      width: "200px"
    },
    {
      key: 4,
      title: '不同医生(科室)算做初诊(单独计算起作用)',
      dataIndex: 'regReDoctorFlag',
      align: "center",
      width: "200px"
    }, {
      key: 5,
      title: '操作',
      dataIndex: 'opertion',
      align: 'center',
      width: "150px",
      render: (text, data) => {
        return (
          <span>
            <Icon type="edit" style={{ color: '#108EE9' }}></Icon>
            <span className='span' onClick={() => this.handleDetailModify(data)}>编辑</span>
            <Divider type="vertical" />
            <Icon type="delete" style={{ color: 'rgba(240,65,52,1)' }}></Icon>
            <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={() => this.handleDetailDelete(data)} >
              <span className='span' style={{ color: 'rgba(240,65,52,1)' }}>删除</span>
            </Popconfirm>
          </span >
        )
      }
    }];
  }

  componentDidMount() {
    this.handleQuery();
    this.getSeleceData();
  }

  handleQuery = () => {
    this.setState({ mainPage: 1, mainLoading: true }, () => {
      this.getTableData();
    })
  }

  // 请求下拉数据
  getSeleceData = async () => {
    try {
      let data = {
        params: [{}],
      }
      let res = await React.$asyncPost(this, '01040252', data);
      this.setState({ hospArr: res.result.hosp, statusArr: res.result.status, reAdmTypeArr: res.result.reAdmType }, () => {
        this.getMainFormData(); // 获取主表表单数据
        this.getDetailFormData(); // 获取明细表表单数据
      });
    } catch (error) {
      this.setState({ mainTableData: [], mainTotal: 0, mainLoading: false })
    }

  }

  // 获取主表表单数据
  getMainFormData = () => {
    let mainFormData = [{
      dataIndex: 'code',
      title: '代码',
      typeCode: 'Input',
      required: 'Y'
    }, {
      dataIndex: 'descripts',
      title: '描述',
      typeCode: 'Input',
      required: 'Y'
    }, {
      dataIndex: 'eNDesc',
      title: '英文描述',
      typeCode: 'Input'
    }, {
      dataIndex: 'reAdmType',
      title: '复诊类型',
      typeCode: 'Select',
      detailItem: this.state.reAdmTypeArr || []
    },
    {
      dataIndex: 'regReAdmDate',
      title: '初诊有效期(天)',
      typeCode: 'Input'
    },
    {
      dataIndex: 'regReDoctorFlag',
      title: '不同医生(科室)算做初诊',
      typeCode: 'Select',
      detailItem: [{ "id": "Y", "descripts": "Y" }, { "id": "N", "descripts": "N" }]
    }, {
      dataIndex: 'startDate',
      title: '开始日期',
      typeCode: 'Date',
      required: 'Y',
      default: 0,
    }, {
      dataIndex: 'stopDate',
      title: '结束日期',
      typeCode: 'Date'
    }];
    this.setState({ mainFormData })
  }

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

  // 请求列表数据
  getTableData = async () => {
    try {
      let { desc, status, mainPage, mainPageSize } = this.state;
      let data = {
        params: [{
          desc,
          status
        }],
        pagination: [{
          pageSize: mainPageSize,
          currentPage: mainPage
        }]
      }
      let res = await React.$asyncPost(this, '01040253', data);
      let mainTableData = res.result && 'rows' in res.result ? Util.addKeyValueToDataSource(res.result.rows) : [];
      this.setState({ mainTableData, mainTotal: res.result.total, mainLoading: false });
    } catch (error) {
      this.setState({ mainTableData: [], mainTotal: 0, mainLoading: false })
    }

  }

  // 新增医院组信息
  handleAdd = () => {
    let { rowData } = this.state;
    if (rowData && 'hospGroupID' in rowData && rowData.hospGroupID) {
      this.setState({ rowData: {} })
    }
    this.mainModalRef && this.mainModalRef.modifyVisible(true);
  }

  // 编辑
  handleModify = (record, e) => {
    e?.stopPropagation();
    this.setState({ rowData: record }, () => {
      this.mainModalRef && this.mainModalRef.modifyVisible(true);
    })
  }

  // 删除
  handleDelete = async record => {
    try {
      if (!(record && record.hospGroupID)) return;
      let data = {
        params: [{
          hospGroupID: record?.hospGroupID
        }]
      }
      let res = await React.$asyncPost(this, '01040258', data);
      message.success(res.errorMessage ? res.errorMessage : '删除成功');
      this.getTableData();
    } catch (error) {
      console.log(error)
    }
  }
  handleDetailDelete = async record => {
    try {
      if (!(record && record.hospGroupLinkID)) return;
      let data = {
        params: [{
          hospGroupLinkID: record?.hospGroupLinkID
        }]
      }
      let res = await React.$asyncPost(this, '01040257', data);
      message.success(res.errorMessage ? res.errorMessage : '删除成功');
      this.getDetailTableData();
    } catch (error) {
      console.log(error)
    }
  }

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

  // 主表保存
  handleMainSave = async values => {
    try {
      let { rowData } = this.state;
      let data = {
        params: [{
          ...values,
          hospGroupID: rowData?.hospGroupID
        }]
      }
      let res = await React.$asyncPost(this, '01040254', data);
      message.success(res.errorMessage ? res.errorMessage : '保存成功');
      this.mainModalRef && this.mainModalRef.modifyVisible(false, 'Y');
      this.setState({ rowData: {} }, () => {
        this.getTableData();
      });
    } catch (error) {
      this.setState({ tableData: [], mainTotal: 0, loading: false })
    }
  }

  // 操作行
  onClickRowPublic = (record) => {
    return {
      // 单击行选中
      onClick: () => {
        console.log("record", record)
        if (this.state.rowID === '') {
          // 保存行数据以及ID
          this.setState({ rowID: record.hospGroupID }, () => {
            this.getDetailTableData()
          });
        } else {
          if (this.state.rowID !== record.hospGroupID) {
            this.setState({ rowID: record.hospGroupID }, () => {
              this.getDetailTableData()
            });
          } else {
            this.setState({ rowID: "", detailTableData: [], detailTotal: 0, detailLoading: false });
          }
        }
      }
    }
  }

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

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

  // 获取主表表单数据
  getDetailFormData = () => {
    let detailFormData = [{
      dataIndex: 'level',
      title: '级别',
      typeCode: 'Input',
    }, {
      dataIndex: 'hospID',
      title: '医院',
      typeCode: 'Select',
      detailItem: this.state.hospArr || [],
      required: 'Y'
    },
    {
      dataIndex: 'regReAdmDate',
      title: '初诊有效期(天)',
      typeCode: 'Input'
    },
    {
      dataIndex: 'regReDoctorFlag',
      title: '不同医生(科室)算做初诊',
      typeCode: 'Select',
      detailItem: [{ "id": "Y", "descripts": "Y" }, { "id": "N", "descripts": "N" }]
    }];
    this.setState({ detailFormData })
  }

  // 获取明细列表数据
  getDetailTableData = async () => {
    try {
      let data = {
        params: [{
          hospGroupID: this.state.rowID
        }]
      }
      let res = await React.$asyncPost(this, '01040255', data);
      let detailTableData = res.result && 'rows' in res.result ? Util.addKeyValueToDataSource(res.result.rows) : [];
      this.setState({ detailTableData, detailTotal: res.result.total, detailLoading: false });
    } catch (error) {
      this.setState({ detailTableData: [], detailTotal: 0, detailLoading: false })
    }
  }

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

  // 添加明细
  handleDetailAdd = () => {
    let { rowID } = this.state;
    if (rowID === '') {
      message.info("请选中一条主记录后再添加！")
      return
    }
    let { detailRowData } = this.state;
    if (detailRowData && 'hospGroupLinkID' in detailRowData && detailRowData.hospGroupLinkID) {
      this.setState({ detailRowData: {} })
    }
    this.detailModalRef && this.detailModalRef.modifyVisible(true);
  }

  // 编辑
  handleDetailModify = record => {
    console.log("recordhandleDetailModify", record)
    this.setState({ detailRowData: record }, () => {
      this.detailModalRef && this.detailModalRef.modifyVisible(true);
    })
  }

  // 明细保存
  handleDetailSave = async values => {
    try {
      let { rowID, detailRowData } = this.state;
      let data = {
        params: [{
          ...values,
          hospGroupLinkID: detailRowData.hospGroupLinkID || '',
          hospGroupID: rowID
        }]
      }
      let res = await React.$asyncPost(this, '01040256', data);
      message.success(res.errorMessage ? res.errorMessage : '保存成功');
      this.detailModalRef && this.detailModalRef.modifyVisible(false, 'Y');
      this.setState({ detailRowData: {} }, () => {
        this.getDetailTableData();
      });
    } catch (error) {
      this.setState({ detailTableData: [], detailTotal: 0, detailLoading: false })
    }
  }

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

  render() {
    let { desc, status, statusArr, mainFormData, rowData, mainTableData, mainTotal, mainPage, mainLoading, detailTableData, detailTotal, detailPage, detailLoading, detailFormData,
      detailRowData,
    } = this.state;

    // 主表操作信息
    let mainOpertion = {
      key: 7,
      title: '操作',
      dataIndex: 'opertion',
      align: 'center',
      width: "150px",
      render: (text, data) => {
        return (
          <span>
            <Icon type="edit" style={{ color: '#108EE9' }}></Icon>
            <span className='span' onClick={(e) => this.handleModify(data, e)}>编辑</span>
            <Divider type="vertical" />
            <Icon type="delete" style={{ color: 'rgba(240,65,52,1)' }}></Icon>
            <Popconfirm title="删除不可恢复，你确定要删除吗?" onCancel={this.handlePopconfirm} onClick={this.handlePopconfirm} onConfirm={(e) => this.handleDelete(data, e)} >
              <span className='span' style={{ color: 'rgba(240,65,52,1)' }}>删除</span>
            </Popconfirm>
          </span >
        )
      }
    }

    // 组件所需参数
    const mainParam = {
      // 表头配置
      columns: [...this.mainColumns, mainOpertion],
      // 表格数据
      data: mainTableData,
      // 数据总条数
      total: mainTotal,
      // 当前页数
      page: mainPage,
      pageSize: "20",
      // 表格的宽度
      x: 750,
      y: store.getState().tableHeight.y + 47,
      height: store.getState().tableHeight.y + 97 + "px",
      isOnRow: true,
      rowClassName: true,
      loading: mainLoading,
    };

    const detailParam = {
      // 表头配置
      columns: this.detailColumns,
      // 表格数据
      data: detailTableData,
      // 数据总条数
      total: detailTotal,
      // 当前页数
      page: detailPage,
      pageSize: '20',
      x: 700,
      y: store.getState().tableHeight.y + 47,
      height: store.getState().tableHeight.y + 97 + 'px',
      loading: detailLoading,
    };
    return (
      <div>
        <Row>
          <Col span={12}>
            <div style={{ paddingRight: '6px', position: 'relative' }}>
              <Card
                size="small"
                title={
                  <div className='card-title-left-img'>
                    <img src={iconListvisits} alt='' />
                    医院组列表
                  </div>
                }
              >
                <div className='table-body-height'>
                  <div style={{ marginBottom: '12px' }}>
                    代码/描述：<Input title="输入内容后可回车检索" placeholder="请输入( Enter )"
                      value={desc} onChange={Util.commonInputChange.bind(this, 'desc')} onPressEnter={this.handleQuery}
                      style={{ width: '150px', marginRight: '15px' }}
                    />
                    状态：<Select
                      allowClear
                      showSearch
                      optionFilterProp="seachprop"
                      placeholder="状态"
                      value={status}
                      onChange={Util.handleSelectChange.bind(this, 'status')}
                      style={{ width: '150px', marginRight: '20px' }}
                    >
                      {statusArr && statusArr.length > 0 ? React.$SelectOptions(statusArr) : ''}
                    </Select>
                    <Button onClick={this.handleQuery}>查询</Button>
                    <Button
                      className="add-btn-nohover"
                      icon="plus"
                      style={{ background: 'rgba(247,128,93,1)', color: '#fff', float: 'right' }}
                      onClick={this.handleAdd}
                    >新增</Button>
                  </div>
                  <PubilcTablePagination
                    param={mainParam}
                    compilePage={this.handleCompilePage}
                    onClickRowPublic={this.onClickRowPublic}
                    setRowClassNamePublic={this.setRowClassNamePublic}
                  />
                </div>
              </Card>
              <div
                style={{
                  width: '6px',
                  background: 'rgba(240, 242, 245, 1)',
                  position: 'absolute',
                  top: 0,
                  right: 0,
                  height: '100%',
                }}
              ></div>
            </div>
          </Col>
          <Col span={12}>
            <Card
              size="small"
              title={
                <div className='card-title-left-img'>
                  <img src={iconListvisits} alt='' />
                  医院组详细列表
                </div>
              }
            >
              <div className='table-body-height'>
                <div style={{ marginBottom: '12px', display: 'flex', justifyContent: 'space-between' }}>
                  <div>
                  </div>
                  <div>
                    <Button
                      className="add-btn-nohover"
                      icon="plus"
                      style={{ background: 'rgba(247,128,93,1)', color: '#fff' }}
                      onClick={this.handleDetailAdd}
                    >新增</Button>
                  </div>
                </div>
                <PubilcTablePagination
                  param={detailParam}
                  compilePage={this.handleDetailCompilePage}
                />
              </div>
            </Card>
          </Col>
        </Row>

        {/* 主表新增弹窗 */}
        <PublicModalFormHooks
          onRef={ref => this.mainModalRef = ref}
          formData={mainFormData}
          rowData={rowData}
          formItemCol={{ labelCol: 5, wrapperCol: 16, col: 24 }}
          recordFormInput={this.recordMainFormInput}
          handleSave={this.handleMainSave}
        />

        {/* 明细新增弹窗 */}
        <PublicModalFormHooks
          onRef={ref => this.detailModalRef = ref}
          formData={detailFormData}
          rowData={detailRowData}
          formItemCol={{ labelCol: 5, wrapperCol: 16, col: 24 }}
          recordFormInput={this.recordDetailFormInput}
          handleSave={this.handleDetailSave}
        />
      </div>
    )
  }
};

export default HospitalGroupMaintenance;