/*
 * Creater:     zxz
 * CreateDate:  2022/03/29
 * Describe：   用户医院分配配置
 * */
import React from 'react';
import { Select, Input, Row, Col, Button, Spin, Divider, Popconfirm, message, Icon, Form, Modal, Card, DatePicker, List } from 'antd';
import { $http } from '../../containers/config/https';
import '../../assets/css/system.css';
import PubilcTablePagination from '../common/PubilcTablePagination.jsx';
import store from './../../store/index';
import moment from 'moment';

const { Option } = Select;
const FormItem = Form.Item;

const formItemLayout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
}
const formItemLayoutUser = {
  labelCol: { span: 4 },
  wrapperCol: { span: 20 },
}

const UserLinkHospital = Form.create()(
  class HospitalMaintenance extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        data: [],
        columns: [],
        total: 0,
        page: 1,
        pageSize: 10,
        baseParms: [],
        values: {},
        hospID: "",
        higherHospID: "",
        hospArr: [],//医院
        userArr: [],//用户
        statusArr: [],
        cityArr: [],
        areasArr: [],
        VillagesArr: [],
        hamletsArr: [],
        heightTable: "",
      }
    }
    componentDidMount() {
      // 初始化设置table的高度以及表体的高度 内容高度 height 
      if (document.querySelector('.ant-table-body')) {
        document.querySelector('.ant-table-body').style.height = store.getState().tableHeight.y - 40 + 'px'
      }
      this.props.onRef && this.props.onRef(this);
      this.gethospArr();
      this.statusArr();
    }

    //获取医院下拉框数据
    gethospArr = () => {
      let data = {
        params: [{
        }],
      }
      $http.post("urlS", this, {
        code: "01040250",
        data: data,
        success: function (res) {
          if (+res.errorCode === 0) {
            this.setState({
              hospArr: res.result,
            },()=>{console.log(this.state.hospArr,"hospArr")})
          } else {
            message.error('失败：' + res.errorMessage);
          }
        },
        error: function (error) {
          message.error('失败：' + error);
        }
      })
    }
    //获取审核状态下拉框数据
    statusArr = () => {
      let data = {
        params: [{
        }],
      }
      $http.post("urlS", this, {
        code: "01040249",
        data: data,
        success: function (res) {
          if (+res.errorCode === 0) {
            this.setState({
              statusArr: res.result
            })
          } else {
            message.error('失败：' + res.errorMessage);
          }
        },
        error: function (error) {
          message.error('失败：' + error);
        }
      })
    }

    setRowClassName = (record) => {
      return record.hospID === this.state.rowId ? 'clickRowStyle' : '';
    }

    FindData = () => {
      const { propMethod: { findData } } = this.props;
      this.showModal(false);
      findData();
      this.reset();
    }
    // 页码改变的回调，参数是改变后的页码及每页条数
    PageChange = (page, pageSize) => {
      this.setState({ page: page, pageSize: pageSize }, () => {
        // 重新调用查询方法
        this.FindData()
      });
    }
    // 条数改变的回调
    onShowSizeChange = (current, size) => {
      this.setState({ page: current, pageSize: size }, () => {
        // 重新调用查询方法
        this.FindData()
      });
    }

    save = () => {
      this.props.form.validateFields((err, values) => {
        const { page, pageSize } = this.state;
        const { data: params } = this.props;
        console.log(params, "params")
        console.log(values, "values")
        if (!err) {
          let data = {
            params: [{
              id: params && params.id ? params.id : "",
              hospID: values.afterHospID || "",
              userID: values.userID || "",
              reason: values.reason || "",
              startDate: values.startDate ? moment(values.startDate).format('YYYY-MM-DD') : undefined,
              stopDate: values.stopDate ? moment(values.stopDate).format('YYYY-MM-DD') : '',
            }],
            pagination: [{
              pageSize: pageSize,
              currentPage: page,
            }]
          }
          $http.post("urlS", this, {
            code: "01040247",
            data: data,
            success: function (res) {
              if (+res.errorCode === 0) {
                if (params && params.hospID) {
                  message.success("修改成功")
                  this.FindData();
                } else {
                  message.success("新增成功")
                  this.FindData();
                }
              } else {
                message.error('失败：' + res.errorMessage);
              }
            },
            error: function (error) {
              message.error('失败：' + error);
            }
          })
        } else {
        }
      })
    }

    reset = () => {
      this.props.form.resetFields();
    }
    //选择医院 加载用户
    handleUser = (e) => {
      if (!e) return
      let data = {
        params: [{
          hospID: e || ""
        }],
      }
      $http.post('urlS', this, {
        code: '01040248',
        data: data,
        success: function (res) {
          if (+res.errorCode === 0) {
            this.setState({
              userArr: res.result,
            })
          } else {
            this.setState({
              userArr: [],
            })
          }
        }
      })
    }
    // 显示分页总条数
    showTotal(total) {
      return `共 ${total} 条`;
    }

    showModal = (bool) => {
      const { propMethod: { showModal } } = this.props;
      showModal(bool);
      this.reset();
    }

    render() {
      const { modalVisible, data: params, propMethod } = this.props;
      const { getFieldDecorator } = this.props.form;
      const { hospArr, userArr , statusArr } = this.state;

      //医院
      let hospOP = []
      let statusOP = []
      let userOP = []
      let oldHosp =[]
      hospArr && hospArr.map(item => {
        oldHosp.push(<Option key={item.id} role={item.descripts + '^' + item.descriptsSPCode} title={item.descripts} value={String(item.id)}>{item.descripts}</Option>)
      }),
      hospArr && hospArr.map(item => {
        hospOP.push(<Option key={item.id} role={item.descripts + '^' + item.descriptsSPCode} title={item.descripts} value={String(item.id)}>{item.descripts}</Option>)
      }),
      statusArr && statusArr.map(item => {
        statusOP.push(<Option key={item.id} role={item.descripts + '^' + item.descriptsSPCode} title={item.descripts} value={String(item.id)}>{item.descripts}</Option>)
      }),
      userArr && userArr.map(item => {
        userOP.push(<Option key={item.id} role={item.descripts + '^' + item.descriptsSPCode} title={item.descripts} value={String(item.id)}>{item.descripts}</Option>)
      })
      return (
        <Modal onCancel={() => this.showModal(false)} title={<span>{params ? params.hospDesc : ''}</span>} visible={modalVisible} width={1200} footer={<div style={{ display: "flex", justifyContent: "flex-end" }}>
          <Button style={{ marginRight: '30px' }} onClick={() => this.showModal(false)}>取消</Button>
          <Button style={{ marginRight: '30px' }} type="primary" onClick={this.save}>{params && params ? "更新" : "新增"}</Button>
          <Button type="primary" onClick={this.reset}>重置</Button>
        </div>} >
          <Row style={{ margin: "0" }}>
            <Col span={24} style={{ paddingLeft: "0px" }}>
              <Card>
                <Form style={{ height: "100%", overflow: "hidden auto" }}>
                  <Row>
                    <Col span={8} className="patNameDom">
                      <FormItem {...formItemLayout} label='医院'>
                        {getFieldDecorator('beforeHospID', {
                          initialValue: params && params.oldHospID ? String(params.oldHospID) : undefined,
                          rules: [{ required: true, message: '请选择医院' }],
                        })(
                          <Select showSearch allowClear optionFilterProp="role" onChange={this.handleUser}>
                            {oldHosp}
                          </Select>
                        )}
                      </FormItem>
                    </Col>
                    <Col span={8}>
                      <FormItem {...formItemLayoutUser} label='用户'>
                        {getFieldDecorator('userID', {
                          initialValue: params && params.userID ? String(params.userID) : undefined,
                          rules: [{ required: true, message: '请选择用户' }],
                        })(
                          <Select showSearch allowClear optionFilterProp="role" >
                            {userOP}
                          </Select>
                        )}
                      </FormItem>
                    </Col>
                    <Col span={8}>
                      <FormItem {...formItemLayout} label='分配医院'>
                        {getFieldDecorator('afterHospID', {
                          initialValue: params && params.hospID ? String(params.hospID) : undefined,
                          rules: [{ required: true, message: '请选择分配医院' }],
                        })(
                          <Select showSearch allowClear optionFilterProp="role" >
                            {hospOP}
                          </Select>
                        )}
                      </FormItem>
                    </Col>
                  </Row>
                  <Row>
                    <Col span={8} className="patNameDom">
                      <FormItem {...formItemLayout} label='理由'>
                        {getFieldDecorator('reason', {
                          initialValue: params && params.reason ? String(params.reason) : '出诊',
                          rules: [{ required: true, message: '请填写理由', },
                          ],
                        })(
                          <Input />
                        )}
                      </FormItem>
                    </Col>
                    <Col span={6} className="starDataDom">
                      <FormItem label='生效日期' {...formItemLayout}>
                        {getFieldDecorator('startDate', {
                          initialValue: params && params.startDate ? moment(params.startDate, "YYYY-MM-DD") : undefined,
                          rules: [{ required: true, message: '请选择开始日期' }],
                        })(
                          <DatePicker style={{ width: '100%' }} placeholder={'开始日期'} disabledDate={(curDate) => {
                            return curDate && curDate > moment().endOf('day');
                          }} />
                        )}
                      </FormItem>
                    </Col>
                    <Col span={6} >
                      <FormItem label='失效日期' {...formItemLayout}>
                        {getFieldDecorator('stopDate', {
                          initialValue: params && params.stopDate ? moment(params.stopDate, "YYYY-MM-DD") : undefined,
                          rules: [{ required: false, message: '' }],
                        })(
                          <DatePicker style={{ width: '100%' }} placeholder={'请选择失效日期'} disabledDate={(curDate) => {
                            return curDate && curDate > moment().endOf('day');
                          }} />
                        )}
                      </FormItem>
                    </Col >
                  </Row>
                </Form>
              </Card>
            </Col>
          </Row>
        </Modal>
      );
    }
  });

class RoleMaintenance extends React.Component {
  constructor() {
    super();
    this.state = {
      // 角色名称
      name: undefined,
      // 关联岗位
      quarters: undefined,
      // 记录状态
      status: undefined,
      // 表格数据
      tableData: [],
      // 表格数据总条数
      total: 0,
      showLoading: true,
      page: 1,
      pageSize: 10,
      selectData: [], // 下拉框数据
      headerHeight: 0,
      columns: [],
      modalVisible: false,
      editData: {},
      hospID: undefined
    };

  }

  componentDidMount() {
    // 初始化列表数据
    this.handleQuery();
    this.getSelectData();
    this.cloumTopData();
    // 组件加载完毕关闭loading
    this.setState({ showLoading: false });
  }

  componentWillUnmount() {
    // 组件销毁前将静止让setState修改state的状态
    this.setState = (state, callback) => { return; }
  }

  // 状态下拉框数据
  getSelectData() {
    let data = {
      params: []
    }
    $http.post('urlS', this, {
      code: "01040249",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          this.setState({ selectData: res.result })
        } else {
          this.setState({ selectData: [] })
        }
      }
    })
  }
  //render 自定义项目名称
  listAdd = (i, j, languageCode) => {
    let { columns } = this.state
    columns.splice(i, j,
      {
        title: languageCode === 'CN' ? "操作" : 'Operation',
        key: 'op',
        align: "center",
        width: 100,
        fixed: 'right',
        render: (text, record) => (
          <span>
            <Icon type="edit" style={{ color: '#108EE9' }}></Icon>
            <span className='span' onClick={() => this.handleCompile(record)}>编辑</span>
            <Divider type="vertical"></Divider>
            <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={() => this.handleCompile(record, "2")} >
              <span className='span' style={{ color: "red" }}>删除</span>
            </Popconfirm>
          </span>
        ),
      },
    )
  }
  // 数据配置
  cloumTopData() {
    var data1 = {
      params: [{
        compontName: "DistributionHospital",
        type: 'C',
      }]
    }
    $http.post('urlS', this, {
      code: "01040073",
      data: data1,
      success: function (res) {
        let errorCode = res.errorCode;
        if (errorCode === '0') {
          let resC = res.result.C

          for (var i = 0; i < resC.length; i++) {
            resC[i].key = i;
          }
          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, // 费用类型table
          }, () => {
            this.listAdd(filterArr.length + 1, 0, 'CN')
          });
        }
      }
    });
  }
  // 调用子组件的连接事件
  onRef = (ref) => {
    this.child = ref
  }

  // 提供修改page和pageSize的回调函数
  compilePage(page, pageSize) {
    // 修改page，或者pageSize
    this.setState({ page: page, pageSize: pageSize }, () => {
      // 重新调用查询方法
      let { status, name, quarters } = this.state;
      this.getTableData(name, status, quarters);
    })
  }
  handleStatus = (v) => {
  }
  // 请求列表数据
  getTableData() {
    let { page, pageSize } = this.state;
    let data = {};
    this.props.form.validateFields((error, values) => {
      if (error) {
        return;
      }
      data = {
        params: [{
          hospDesc: values.hospDesc ? values.hospDesc : '',
          userDesc: values.userDesc ? values.userDesc : '',
          status: values.hospStatus ? values.hospStatus : '',
        }],
        pagination: [{
          pageSize: pageSize,
          currentPage: page,
          sortColumn: "",
          sortOrder: ""
        }]
      };
      $http.post('urlS', this, {
        code: "01040246",
        data: data,
        success: function (res) {
          if (+res.errorCode === 0 && res.result) {
            this.setState({ tableData: res.result.Data, total: res.result.TotalCount }, () => {
              // 数据加载成功关闭loading
              this.child.handleLoading()
            })
          } else {
            this.setState({ tableData: [], total: 0 }, () => {
              // 数据加载成功关闭loading
              this.child.handleLoading();
            })
          }
        },
        error: function () {
          this.setState({ tableData: [], total: 0 }, () => {
            // 数据加载成功关闭loading
            this.child.handleLoading();
          })
        }
      });
    });

  }

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

  // 新增跳转到新增界面
  handleAdd = () => {
    this.setState({ editData: undefined });
    this.showModal(true);
  }

  // 编辑
  handleCompile = (record, num) => {
    if (num == "2") {
      let data = {
        params: [{
          id: record.id,
          updateUserID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).userID : "",
        }],
      }
      $http.post("urlS", this, {
        code: "01040251",
        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 {
      this.setState({
        editData: record,
        hospID: record && record.oldHospID ? record.oldHospID : ''
      }, () => {
        this.showModal(true);
      });
    }
  }
  
  //控制模态框显示
  showModal = (bool) => {
    let { hospID } = this.state;
    this.setState({ modalVisible: bool }, () => {
      this.userChild && this.userChild.handleUser(hospID)
    });
  }

  handleUserRef = ref => {
    this.userChild = ref;
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    // 组件所需参数
    const param = {
      // 表头配置
      columns: this.state.columns,
      // 表格数据
      data: this.state.tableData,
      // 数据总条数
      total: this.state.total,
      // 当前页数
      page: this.state.page,
      // 表格的宽度
      x: '115%',
      y: store.getState().tableHeight.y - 45 - this.state.headerHeight,
      height: store.getState().tableHeight.y - this.state.headerHeight + 'px',
    }
    let statusoP = []
    this.state.selectData && this.state.selectData.map(item => {
      statusoP.push(<Option key={item.id} role={item.descripts + '^' + item.descriptsSPCode} title={item.descripts} value={String(item.id)}>{item.descripts}</Option>)
    });
    return (
      <Spin tip="加载中..." spinning={this.state.showLoading}>
        <div>
          <Form>
            <Row style={{ margin: '23px 0 0 0' }}>
              <Col span={5} >
                <FormItem {...formItemLayout} label='医院描述'>
                  {getFieldDecorator('hospDesc', {
                    //initialValue: params && params.healBureauID ? String(params.healBureauID) : undefined,
                    rules: [{ required: false, message: '' }],
                  })(
                    <Input title="输入内容后可回车检索" placeholder="请输入( Enter )" onPressEnter={this.handleQuery} />
                  )}
                </FormItem>
              </Col>
              <Col span={4} >
                <FormItem {...formItemLayout} label='用户'>
                  {getFieldDecorator('userDesc', {
                    //initialValue: undefined,
                    rules: [{ required: false, message: '' }],
                  })(
                    <Input title="输入内容后可回车检索" placeholder="请输入( Enter )" onPressEnter={this.handleQuery} />
                  )}
                </FormItem>
              </Col>
              <Col span={6}>
                <Button onClick={this.handleQuery} style={{ margin: '4px 15px 20px 20px', background: 'rgba(255,255,255,1)' }}>查询</Button>
              </Col>
              <Col span={7}>
              </Col>
              <Col span={2}>
                <Button icon="plus" onClick={this.handleAdd} style={{ background: 'rgba(247,128,93,1)', color: '#fff', margin: '4px 0 0 0' }}>新增</Button>
              </Col>
            </Row>
          </Form>
        </div>
        <div style={{ width: '100%', height: '10px', background: '#f0f2f5' }}></div>
        <div style={{ padding: "24px 24px 12px 24px" }} className="table-body-height">
          {/* handelThis将夫组件的属性与方法给子组件访问 */}
          <PubilcTablePagination param={param} handelThis={this} onRef={this.onRef} />
        </div>
        <UserLinkHospital onRef={this.handleUserRef} data={this.state.editData} modalVisible={this.state.modalVisible} hospID={this.state.hospID} propMethod={{ showModal: this.showModal, findData: this.handleQuery }} />
      </Spin>
    )
  }
}
export default Form.create()(RoleMaintenance);