//卡信息配置
import React from 'react';
import { Select, Row, Col, Button, Spin, Divider, Popconfirm, message, Icon, Form, Table } from 'antd';
import { $http } from 'containers/config/https';
import 'assets/css/system.css';
import store from 'store/index';
import HBCardConfigModal from './component/HBCardConfigModal.jsx';
import CommonPagination from 'components/pagination';

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

const formItemLayout = {
  labelCol: { span: 10 },
  wrapperCol: { span: 14 },
}
const formItemLayoutTop = {
  labelCol: { span: 9 },
  wrapperCol: { span: 15 },
}
class RoleMaintenance extends React.Component {
  constructor() {
    super();
    var userData = JSON.parse(sessionStorage.getItem('userData'));
    this.state = {
      // 角色名称
      name: undefined,
      // 关联岗位
      quarters: undefined,
      // 记录状态
      status: undefined,
      // 表格数据
      tableData: [],
      // 表格数据总条数
      total: 0,
      showLoading: true,
      page: 1,
      pageSize: 20,
      selectData: {}, // 下拉框数据
      headerHeight: 0,
      defaultFlag: false,
      modalVisible: false,
      editData: {},
      total: 0,
      page: 1,
      pageSize: 20,
      size: 'small',
      search: '',
      userData: userData
    };
    this.columns = [{
      key: 1,
      title: '医院',
      dataIndex: 'hospDesc',
      align: 'center',
      width: '150px'
    },
    {
      key: 2,
      title: '角色',
      dataIndex: 'groupDesc',
      align: 'center',
      width: '100px'
    },
    {
      key: 3,
      title: '卡类型',
      dataIndex: 'cardTypeDesc',
      align: 'center',
      width: '80px'
    }, {
      title: '证件类型',
      dataIndex: 'credTypeDesc',
      align: 'center',
      width: '80px'
    },
    {
      key: 4,
      title: '性别',
      dataIndex: 'sexDesc',
      align: 'center',
      width: '50px'
    },
    {
      key: 5,
      title: '民族',
      dataIndex: 'nationDesc',
      align: 'center',
      width: '50px'
    },
    {
      key: 6,
      title: '患者类别',
      dataIndex: 'patTypeDesc',
      align: 'center',
      width: '100px'
    },
    {
      key: 7,
      title: '国家',
      dataIndex: 'countryDesc',
      align: 'center',
      width: '50px'
    },
    {
      key: 8,
      title: '默认职业',
      dataIndex: 'occupationDesc',
      align: 'center',
      width: '100px'
    },
    {
      key: 9,
      title: '职业必填标志',
      dataIndex: 'occupationRequireFlag',
      align: 'center',
      width: '100px'
    },
    {
      key: 10,
      title: '地址',
      dataIndex: 'provDesc',
      align: 'center',
      width: '250px',
      render: (text, record) => {
        let add = record.provinceDesc + '，' + record.cityDesc + '，' + record.areaDesc;
        add = record.villageDesc ? add + '，' + record.villageDesc : add;
        add = record.hamletDesc ? add + '，' + record.hamletDesc : add;
        return <span>{add}</span>
      }
    },
    {
      key: 11,
      title: '必填项',
      dataIndex: 'requireFlagDesc',
      align: 'center',
      width: '250px',
    },
    {
      title: '操作',
      key: 12,
      align: "center",
      width: '100px',
      render: (text, record) => (
        <span>
          <Icon type="edit" style={{ color: '#108EE9' }}></Icon>
          <span className='span' onClick={() => this.handleCompile(record)}>编辑</span>
          <Divider type="vertical" />
          <Icon type="delete" style={{ color: 'rgba(240,65,52,1)' }}></Icon>
          <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={() => this.handleDetele(record)} >
            <span className='span' style={{ color: 'rgba(240,65,52,1)' }}>删除</span>
          </Popconfirm>
        </span>
      ),
    }
    ]
  }

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

  //获取医院信息
  loadHospitalMsg() {
    var params = {
      params: [{
        // hospitalId:this.state.userData.hospDr,
        hospID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).hospID : '',
        logonHospID: this.state.userData.hospID,
        logonGroupID: this.state.userData.groupID,
      }]
    }
    $http.post('urlDeault', this, {
      code: "01040001",
      data: params,
      success: function (res) {
        if (res.errorCode === '0') {
          this.setState({
            supHealthBur: res.depDoctor
          })
        }
      }
    });
  }
  //获取对应的医院基础信息数据
  getBaseParams = () => {
    let data = {
      params: [{
        hospID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).hospID : ''
      }],
    }
    $http.post("urlS", this, {
      code: "01040059",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          this.setState({
            cardType: res.cardType
          })
        } else {

        }
      },
      error: function (error) {

      }
    });
    $http.post("urlS", this, {
      code: "03030027",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          this.setState({
            group: res.result.Data
          })
        } else {

        }
      },
      error: function (error) {

      }
    });
  }

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

  // 请求列表数据
  getTableData = () => {
    let { page, pageSize } = this.state;
    let data = {};
    this.props.form.validateFields((error, values) => {
      if (error) {
        return;
      }
      data = {
        params: [{
          hospID: values && values.hospID ? values.hospID : '',
          groupID: values && values.groupID ? values.groupID : '',
          cardTypeID: values && values.cardTypeID ? values.cardTypeID : '',
        }],
        pagination: [{
          pageSize: pageSize,
          currentPage: page,
          sortColumn: "",
          sortOrder: ""
        }]
      };
      $http.post('urlS', this, {
        code: "03030019",
        data: data,
        success: function (res) {
          if (+res.errorCode === 0 && res.result) {
            this.setState({ tableData: res.result.Data, total: res.result.TotalCount }, () => {
              // 数据加载成功关闭loading
            })
          } else {
            this.setState({ tableData: [], total: 0 }, () => {
              // 数据加载成功关闭loading
            })
          }
        },
        error: function () {
          this.setState({ tableData: [], total: 0 }, () => {
            // 数据加载成功关闭loading
          })
        }
      });
    });

  }
  // 修改page和pageSize 跳转至---
  onChange = (e) => {
    this.setState({ page: e, pageSize: this.state.pageSize, }, () => {
      // 重新调用查询方法
      this.getTableData();
    })
  }
  //下拉选择页数
  onShowSizeChange = (page, pageSize) => {
    // console.log("page",page,"pagesize",pageSize)
    this.setState({ page: 1, pageSize: pageSize, search: "search" }, () => {
      // 重新调用查询方法
      this.getTableData();
    })
  }
  // 显示分页总条数
  showTotal(total) {
    return `共 ${total} 条`;
  }
  // 查询
  handleQuery = () => {
    this.setState({ page: 1, pageSize: this.state.pageSize, search: "search" }, () => {
      // 重新调用查询方法
      this.getTableData();
    })
  }

  // 新增跳转到新增界面
  handleAdd = () => {
    this.modalChildRef.showModal({}, "")
  }
  handleDetele = (record) => {
    let data = {
      params: [{
        updateUserID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).userID : "",
        id: record.id
      }]
    }
    $http.post('urlADS', this, {
      code: '03030022',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          message.success('删除成功');
          // 刷新列表数据
          this.handleQuery();
        }
      }
    })
  }
  // 编辑
  handleCompile = (record) => {
    this.modalChildRef.showModal(record, "1")
  }
  setDefaultFlag = (v) => {
    this.setState({ defaultFlag: v });
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const { cardType, group, supHealthBur } = this.state
    // 组件所需参数
    const param = {
      // 表头配置
      columns: this.columns,
      // 表格数据
      data: this.state.tableData,
      // 数据总条数
      total: this.state.total,
      // 当前页数
      page: this.state.page,
      // 表格的宽度
      x: '100%',
      y: store.getState().tableHeight.y + 81 - this.state.headerHeight,
      height: store.getState().tableHeight.y + 50 - this.state.headerHeight + 'px',
    }
    // 医院
    let supHealthBurOps = []
    supHealthBur && supHealthBur.map(item => {
      supHealthBurOps.push(<Option key={item.id} role={item.descripts + '^' + item.descriptsSPCode} title={item.descripts} value={String(item.id)}>{item.descripts}</Option>)
    })
    // 角色
    let groupOpt = []
    group && group.map(item => {
      groupOpt.push(<Option key={item.id} role={item.descripts + '^' + item.descriptsSPCode} title={item.descripts} value={String(item.id)}>{item.descripts}</Option>)
    })
    // 卡类型
    let cardTypeOpt = []
    cardType && cardType.map(item => {
      cardTypeOpt.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={4}>
                <FormItem {...formItemLayoutTop} label='医院'>
                  {getFieldDecorator('hospID', {
                    initialValue: undefined,
                    rules: [{ required: false, message: '' }],
                  })(
                    <Select showSearch allowClear optionFilterProp="role" >
                      {supHealthBurOps}
                    </Select>
                  )}
                </FormItem>
              </Col>
              <Col span={4}>
                <FormItem {...formItemLayoutTop} label='角色'>
                  {getFieldDecorator('groupID', {
                    initialValue: undefined,
                    rules: [{ required: false, message: '' }],
                  })(
                    <Select showSearch allowClear optionFilterProp="role" >
                      {groupOpt}
                    </Select>
                  )}
                </FormItem>
              </Col>
              <Col span={4}>
                <FormItem {...formItemLayoutTop} label='卡类型'>
                  {getFieldDecorator('cardTypeID', {
                    initialValue: undefined,
                    rules: [{ required: false, message: '' }],
                  })(
                    <Select showSearch allowClear optionFilterProp="role" >
                      {cardTypeOpt}
                    </Select>
                  )}
                </FormItem>
              </Col>
              <Col span={1} style={{ margin: "0 16px" }}>
                <FormItem {...formItemLayout}>
                  {getFieldDecorator('btn', {
                    initialValue: undefined,
                    rules: [{ required: false, message: '' }],
                  })(
                    <Button onClick={this.handleQuery} style={{ margin: '4px 15px 20px 0', background: 'rgba(255,255,255,1)' }}>查询</Button>
                  )}
                </FormItem>
              </Col>
              <Col span={2}>
                <FormItem {...formItemLayout}>
                  {getFieldDecorator('newAdd', {
                    initialValue: undefined,
                    rules: [{ required: false, message: '' }],
                  })(
                    <Button icon="plus" onClick={this.handleAdd} style={{ background: 'rgba(247,128,93,1)', color: '#fff', margin: '4px 0 0 0' }}>新增配置</Button>
                  )}
                </FormItem>
              </Col>
            </Row>
          </Form>
        </div>
        <div style={{ width: '100%', height: '10px', background: '#f0f2f5' }}></div>
        <div style={{ padding: '24px 0 0 0' }} className="table-body-height">
          <Table
            columns={param.columns}
            dataSource={param.data}
            pagination={false}
            rowKey={record => record.key}
            bordered
            scroll={{ x: 1460, y: store.getState().tableHeight.y + 10 }}
            style={{ height: store.getState().tableHeight.y + 60 + 'px', overflow: "auto" }}
          />
          <CommonPagination size={this.state.size} pageSize={this.state.pageSize} current={this.state.page} total={this.state.total} search={this.state.search}
            onShowSizeChange={this.onShowSizeChange.bind(this)} complete={true} dataSource={this.state.tableData}
            onChange={this.onChange.bind(this)} />
        </div>
        <HBCardConfigModal modalRef={this.modalRef} defaultFlag={this.state.defaultFlag} propMethod={{ showModal: this.showModal, findData: this.getTableData }}
          supHealthBur={this.state.supHealthBur} />
      </Spin>
    )
  }
}
export default Form.create()(RoleMaintenance);