import React from 'react';
import { Table, Popconfirm, Icon, message, Modal, Form, Divider, Select, Row, Col, Button } from 'antd';
import { $http } from '../../containers/config/https';
import store from '../../store';

import CommonPagination from 'components/pagination/index';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';

const { Option } = Select;
const formItemLayout = {    // label 和input宽度
  labelCol: { span: 8 },
  wrapperCol: { span: 14, offset: 2 },
};

class OPClassifyPayWay extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false, //加载状态标志
      visible: false, //弹窗显示状态标志
      motalTitle: '', //弹窗标题
      modalState: '', //弹窗点击提交时判断是否修改或增加标志
      selectHosp: JSON.parse(window.sessionStorage.userData).hospID, //医院选择 --- 查询条件
      selectPayWay: '', //支付方式选择 --- 查询条件
      selectCosttype: '', //支付类型选择 --- 查询条件
      hospitaData: [], //医院下拉框数据 --- 查询
      payWayData: [], //支付方式下拉框数据 --- 查询
      costtypeData: [], //支付类型下拉框数据 --- 查询
      hospita: [], //表单医院下拉框数据
      payWay: [], //表单支付方式下拉框数据
      costtype: [], //表单支付类型下拉框数据
      tableData: [], // 表格数据
      columns: [], //表格列表
      total: 0,  // 表格数据总条数
      page: 1, //当前页数
      pageSize: 10, //每页显示条数
      delClassifyPayWayID: '', //删除医院支付方式分类表记录ID
      updateID: '', //修改表单ID

      languageTable1: {}, // 国际化Table1
      languageTable2: {}, // 国际化Table2
      languageData: {}, // 国际化语言包
      language: {},   // 国际化语言
      languageCode: JSON.parse(window.sessionStorage.userData).language, // 国际化语言标识
    };
    // this.columns = [
    //   {
    //     title: '医院',
    //     dataIndex: 'hospDesc',
    //     key: 'hospDesc',
    //     width: '320px',
    //     align: "center",
    //   },
    //   {
    //     title: '支付方式',
    //     dataIndex: 'payWayDesc',
    //     key: 'payWayDesc',
    //     width: '300px',
    //     align: "center",
    //   },
    //   {
    //     title: '支付类型',
    //     dataIndex: 'costtypeData',
    //     key: 'costtypeData',
    //     width: '300px',
    //     align: "center",
    //   },
    //   {
    //     title: '操作',
    //     key: 'op',
    //     align: "center",
    //     render: (text, record) => (
    //       <span>
    //         <span className='span' onClick={() => this.showModal(record)}><Icon type="edit" />修改</span>
    //         <Divider type="vertical" />
    //         <Popconfirm
    //           title="确定要删除吗?"
    //           onConfirm={this.delConfirm}
    //           okText="是"
    //           cancelText="否"
    //         >
    //           <span style={{ color: '#f00' }} className='span' onClick={() => this.setState({ delClassifyPayWayID: record.id })}><Icon type="delete" />删除</span>
    //         </Popconfirm>
    //       </span>
    //     ),
    //   },
    // ];
  }


  componentDidMount() {
    this.tableList("OPClassifyPayWay","OPClassifyPayWay");
    //初始化列表数据
    this.handleQuery();
    //医院下拉框
    this.getHospitalData();
    //支付方式下拉框
    this.getPayWayData();
    //支付类型下拉框
    this.getCosttypeData();
  }

  //render 自定义项目名称
  listAdd = (i, j, languageCode) => {
    let { columns } = this.state
    columns.splice(i, j,
      {
        title: languageCode === 'CN' ? "操作" : 'Operation',
        key: 'op',
        align: "center",
        render: (text, record) => (
          <span>
            <span className='span' onClick={() => this.showModal(record)}><Icon type="edit" />{languageCode === 'CN' ? "修改" : 'Alter'}</span>
            <Divider type="vertical" />
            <Popconfirm
              title={languageCode === 'CN' ? "确定要删除吗?" : 'You sure you want to delete it?'}
              onConfirm={this.delConfirm}
              okText={languageCode === 'CN' ? "是" : 'Yes'}
              cancelText={languageCode === 'CN' ? "否" : 'No'}
            >
              <span style={{ color: '#f00' }} className='span' onClick={() => this.setState({ delClassifyPayWayID: record.id })}><Icon type="delete" />{languageCode === 'CN' ? "删除" : 'Delete'}</span>
            </Popconfirm>
          </span>
        ),
      },
    )
  }
  onColumnRef = (ref) => {
    console.log(ref)
    this.columnRef = ref;
  }
  // 获取主列表columns
  tableList = (reactCode, compontName) => {
    var data = {
      params: [{
          "reactCode": [reactCode],
          "compontName": compontName,
          "type": "C"
      }]
  }
    console.log(1, data)
    $http.post('urlS', this, {
        code: '01040073',
        data: data,
        success: function (res) {
            if (+res.errorCode === 0) {
                let resC = res.result.C
                let { languageCode } = this.state
                for (var i = 0; i < resC.length; i++) {
                    resC[i].key = i;
                }
                if (languageCode === "EN") {
                    resC.map((item, i) => {
                        item.title = item.enDescripts
                    })
                }
            
                if (languageCode === "CN") {
                    resC.map((item, i) => {
                        item.title = item.descripts
                    })
                }
                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,
                  languageTable1: res.result.B || {},  // 国际化Table1
                  languageTable2: res.result.C || {},  // 国际化Table2
                  languageData: res.result.language || {},  // 国际化语言包
                }, () => {
                  this.LanCNEN(this.state.languageCode)
                  this.listAdd(filterArr.length+1, 0,languageCode);
                })
            }
        }
    })
  }

  LanCNEN = (code) => {
    let { languageData } = this.state
    this.setState({
        language: languageData[code]
    })
  }

  //初始化列表数据
  handleQuery = () => {
    let { page, pageSize, selectHosp, selectPayWay, selectCosttype } = this.state;
    let data = {}
    data = {
      params: [{
        hospID: selectHosp,
        paywayID: selectPayWay,
        costtype: selectCosttype
      }],
      pagination: [{
        pageSize: pageSize,
        currentPage: page,
        sortColumn: 'code',
        sortOrder: 'asc'
      }]
    }
    $http.post('urlS', this, {
      code: '05100252',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0 && res.result) {
          for (var i = 0; i < res.result.length; i++) {
            res.result[i].key = i;
          }
          this.setState({ tableData: res.result.Data, total: res.result.TotalCount, loading: false })
        } else {
          this.setState({ tableData: [], total: 0, loading: false })
        }
      }
    })
  }

  // 页码改变的回调，参数是改变后的页码及每页条数
  appPageChange = (page, pageSize) => {
    this.setState({
        page: page,
        pageSize: pageSize,
    }, () => {
        // 重新调用查询方法
        this.handleQuery();
    });
  }

  // 条数改变的回调
  apponShowSizeChange = (current, size) => {
    this.setState({
        page: current,
        pageSize: size,
    }, () => {
        // 重新调用查询方法
        this.handleQuery();
    });
  }

  //支付方式下拉框数据
  getPayWayData = () => {
    var data = {
      params: [{
      }]
    }
    let payWay = []
    $http.post("urlS", this, {
      code: '05100033',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0 && res.payMode) {
          for (var i = 0; i < res.payMode.length; i++) {
            payWay.push(<Option value={String(res.payMode[i].id)} key={i + "P"} >{res.payMode[i].descripts}</Option>)
          }
          this.setState({ payWayData: payWay, payWay: payWay, })
        }
      },
      error: function (err) {
        this.setState({ errMsg: "数据加载失败，请重试！" })
      }
    })
  }

  //支付类型下拉框数据
  getCosttypeData = () => {
    let costtypeData = []
    costtypeData.push(<Option value="ZF" >自付</Option>)
    costtypeData.push(<Option value="YB" >医保</Option>)
    costtypeData.push(<Option value="JZ" >记账</Option>)
    costtypeData.push(<Option value="TH" >第三方</Option>)
    this.setState({ costtypeData: costtypeData, costtype: costtypeData, })
  }

  //医院下拉框数据
  getHospitalData = () => {
    var data = {
      params: [{
        logonGroupID: JSON.parse(window.sessionStorage.userData).groupID,
        logonHospID: JSON.parse(window.sessionStorage.userData).hospID,
        dataType: "combo",
      }]
    }
    let hospital = []
    $http.post("urlS", this, {
      code: '05100046',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0 && res.Hosp) {
          for (var i = 0; i < res.Hosp.length; i++) {
            hospital.push(<Option value={String(res.Hosp[i].id)} key={i + "H"} >{res.Hosp[i].descripts}</Option>)
          }
          this.setState({ hospitaData: hospital, hospital: hospital, })
        }
      },
      error: function (err) {
        this.setState({ errMsg: "数据加载失败，请重试！" })
      }
    })
  }

  //医院选择 --- 查询条件
  onChangeHosp = (e) => {
    this.setState({ selectHosp: e });
  }
  
  //支付方式选择 --- 查询条件
  onChangePayWay = (e) => {
    this.setState({ selectPayWay: e });
  }
  
  //支付类型选择 --- 查询条件
  onChangeCosttype = (e) => {
    this.setState({ selectCosttype: e });
  }

  //新增弹窗显示
  showModal = (params) => {
    if (params === 'add') {
      this.setState({
        modalState: 'add',
        visible: true,
        motalTitle: "新增",
      });
      this.props.form.setFieldsValue({
        'Hosp': JSON.parse(window.sessionStorage.userData).hospID,
        'PayWay': undefined,
        'Costtype': undefined,
      });
    } else {
      this.setState({
        modalState: 'update',
        updateID: params.id,
        visible: true,
        motalTitle: "修改",
      });
      this.props.form.setFieldsValue({
        'Hosp': params.hosp,
        'PayWay': params.payWay,
        'Costtype': params.costtypeData,
      });
    }
  };

  //弹窗点击取消
  handleCancel = () => {
    this.setState({ visible: false, });
  };

  //弹窗点击确定
  handleOk = () => {
    this.props.form.validateFields((err, values) => {
      if (err) {
        return;
      }
      let data = {};
      let code = '';
      if (this.state.modalState === 'add') {
        code = '05100254';
      } else if (this.state.modalState === 'update') {
        code = '05100255';
      }
      data = {
        params: [{
          ID: this.state.updateID,
          userID: JSON.parse(window.sessionStorage.userData).userID,
          createUserID: JSON.parse(window.sessionStorage.userData).userID,
          hospID: values.Hosp,
          paywayID: values.PayWay,
          costtype: values.Costtype,
        }]
      }
      $http.post('urlS', this, {
        code: code,
        data: data,
        success: function (res) {
          if (+res.errorCode === 0) {
            message.success(res.errorMessage);
            this.handleQuery();
            this.setState({ loading: false, visible: false });
          }
        }
      })
    })
  };

  //删除确认
  delConfirm = (e) => {
    this.handleDel();
  }

  //删除操作
  handleDel = () => {
    let data = {
      params: [{
        classifyPayWayID: this.state.delClassifyPayWayID,
        changeID: JSON.parse(window.sessionStorage.userData).userID
      }]
    };
    $http.post('urlS', this, {
      code: "05100253",
      data: data,
      success: function (res) {
        let errorCode = res.errorCode;
        if (errorCode === '0') {
          message.success(res.errorMessage);
          this.handleQuery() // 查询
        }
      }
    });
  }

  render() {
    let { hospitaData, payWayData, costtypeData, hospital, payWay, costtype, language,} = this.state;
    const { getFieldDecorator } = this.props.form;
    return (
      <div>
        <div style={{ width: '100%', height: '100%' }}>
          <Row style={{ minHeight: '80px', padding: '24px 24px 24px 24px' }}>
            <Col span={6}>
              <span>{language.OPClassifyPayWayhospitaData && language.OPClassifyPayWayhospitaData.descripts}：</span>
              <Select style={{ width: '150px' }} value={this.state.selectHosp} allowClear placeholder={language.OPClassifyPayWayhospitaData && language.OPClassifyPayWayhospitaData.message} onChange={this.onChangeHosp} >
                {hospitaData}
              </Select>
            </Col>
            <Col span={6}>
              <span>{language.OPClassifyPayWaypayWayData && language.OPClassifyPayWaypayWayData.descripts}：</span>
              <Select style={{ width: '150px' }} allowClear placeholder={language.OPClassifyPayWaypayWayData && language.OPClassifyPayWaypayWayData.message} onChange={this.onChangePayWay} >
                {payWayData} 
              </Select>
            </Col>
            <Col span={6}>
              <span>{language.OPClassifyPayWaycosttypeData && language.OPClassifyPayWaycosttypeData.descripts}：</span>
              <Select style={{ width: '150px' }} allowClear placeholder={language.OPClassifyPayWaycosttypeData && language.OPClassifyPayWaycosttypeData.message} onChange={this.onChangeCosttype} >
                {costtypeData}
              </Select>
            </Col>
            <Col span={3} style={{ textAlign: 'right' }}>
              <Button type="primary" onClick={() => this.handleQuery()} icon="search" >{language.OPClassifyPayWayhandleQuery && language.OPClassifyPayWayhandleQuery.descripts}</Button>
            </Col>
            <Col span={3} style={{ textAlign: 'center' }}>
              <Button type="primary" onClick={() => this.showModal('add')} icon="plus" style={{ background: '#F7805D', color: '#FFFFFF', borderColor: '#F7805D' }} >
                {language.OPClassifyPayWayshowModal && language.OPClassifyPayWayshowModal.descripts}
              </Button>
              <Form layout="inline">
                <Modal
                  visible={this.state.visible}
                  title={this.state.motalTitle}
                  onOk={() => this.handleOk(this.state.modalState)}
                  onCancel={this.handleCancel}
                  width='600px'
                  footer={[
                    <Button key="back" onClick={this.handleCancel}>
                      返回
                    </Button>,
                    <Button key="submit" type="primary" loading={this.state.loading} onClick={this.handleOk}>
                      提交
                    </Button>,
                  ]}
                >
                  <Row>
                    <Col span={24}>
                      <Form.Item label="医院" {...formItemLayout} >
                        {getFieldDecorator("Hosp", {
                          initialValue: undefined,
                          rules: [{ required: true, message: '医院不能为空' }]
                        })(
                          <Select style={{ width: '150px' }} allowClear placeholder="请选择医院" >
                            {hospital}
                          </Select>
                        )}
                      </Form.Item>
                    </Col>
                    <Col span={24}>
                      <Form.Item label="支付方式" {...formItemLayout}>
                        {getFieldDecorator("PayWay", {
                          initialValue: undefined,
                          rules: [{ required: true, message: '支付方式不能为空' }]
                        })(
                          <Select style={{ width: '150px' }} allowClear placeholder="请选择支付方式" >
                            {payWay}
                          </Select>
                        )}
                      </Form.Item>
                    </Col>
                    <Col span={24}>
                      <Form.Item label="支付类型" {...formItemLayout}>
                        {getFieldDecorator("Costtype", {
                          initialValue: undefined,
                          rules: [{ required: true, message: '支付类型不能为空' }]
                        })(
                          <Select style={{ width: '150px' }} allowClear placeholder="请选择支付类型" >
                            {costtype}
                          </Select>
                        )}
                      </Form.Item>
                    </Col>
                  </Row>
                </Modal>
              </Form>
            </Col>
          </Row>
        </div>
        <div style={{ widht: '100%', height: '10px', background: '#f0f2f5' }}></div>
        <div style={{ padding: 24 }}>
          <Table
              style={{ height: store.getState().tableHeight.y + 65 + 'px' }}
              dataSource={this.state.tableData}
              columns={this.state.columns}
              className='TableA'
              //rowClassName="editable-row"
              pagination={false}
              scroll={{ x: 900, y: store.getState().tableHeight.y }}
              bordered
              loading={this.state.loading}
          />
          <CommonPagination size="small" current={this.state.page} total={this.state.total} search='search'
              onShowSizeChange={this.apponShowSizeChange} complete={true} dataSource={this.state.tableData}
              onChange={this.appPageChange} />
          <ColumnAuthoritysModel
              clientWidth='900px'
              compontName='OPClassifyPayWay'
              configType="C"
              onRef={this.onColumnRef}
              reloadData={this.tableList}
          />
        </div>
      </div>
    )
  }
}

const OPClassifyPayWayForm = Form.create()(OPClassifyPayWay);
export default OPClassifyPayWayForm;