// 消耗统计
import React, { Component } from 'react';
import { Modal, Input, Select, Form, Button, Row, Col, Switch, DatePicker, message } from 'antd';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import { $http } from 'containers/config/https';
import { handleExcel } from 'tools/handleExcel.js';
import Moment from 'moment';
import PubilcTablePagination from 'pages/common/PubilcTablePagination.jsx';
import "../style/index.less";

let { Option } = Select;

class ConsumptionStatistics extends Component {
  constructor(props) {
    super(props);
    var userData = JSON.parse(sessionStorage.getItem('userData'));
    this.state = {
      userData,
      visible: false,
      columns: [],
      parameterSetting: null,
      tableData: [],
      page: 1,
      pageSize: 10,
      allConsume: false, // 根据全院消耗
    };
    this.columns = [
      { title: '药品代码', dataIndex: 'stockCode', key: '1', width: '100px', align: "center" },
      { title: '药品规格', dataIndex: 'stockDesc', key: '2', width: '100px', align: "center" },
      {
        title: '单位', dataIndex: 'stockSpec', key: '3', width: '150px', align: "center"
      },
      { title: '进价', dataIndex: 'rp', key: '4', width: '150px', align: "center" },
      { title: '售价', dataIndex: 'sp', key: '5', width: '150px', align: "center" },
      {
        title: '消耗数量', dataIndex: 'consumeQty', key: '6', width: '150px', align: "center"
      },
      {
        title: '平均日消耗数量', dataIndex: 'averageQty', key: '7', width: '150px', align: "center"
      },
      { title: '总库存数', dataIndex: 'sumQty', key: '8', width: '150px', align: "center" },
      {
        title: '采购数量', dataIndex: 'purQty', key: '9', width: '150px', align: "center"
      },
      {
        title: '生产企业', dataIndex: 'manfDesc', key: '10', width: '150px', align: "center"
      },
      { title: '供应商', dataIndex: 'vendorDesc', key: '11', width: '150px', align: "center" }
    ];
  }

  componentDidMount() {
    this.props.onRef(this);
  }

  onRef = ref => {
    this.child = ref;
  }

  // 获取初始化数据
  getParameterSetting = () => {
    let data = {
      params: []
    }
    $http.post('urlS', this, {
      code: "02020247",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          this.setState({
            parameterSetting: res
          }, () => {
            this.child && this.child.handleLoading && this.child.handleLoading();
          })
        }
      }
    })
  }

  // 打开弹窗
  showModal = () => {
    let { parameterSetting, columns } = this.state;
    this.setState({ visible: true }, () => {
      if (!(columns && columns.length > 0)) {
        this.getColumns();
      }
      if (!parameterSetting) {
        this.getParameterSetting();
      }
      // this.handleQuery();
    })
  }

  // 关闭弹窗
  handleCancelModal = () => {
    this.setState({ visible: false })
  }

  // 获取表头数据
  getColumns = () => {
    let { userData } = this.state;
    let data = {
      params: [{
        compontName: "ConsumptionStatistics",
        type: 'C',
      }]
    }
    $http.post('urlS', this, {
      code: '01040073',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          let arr = res.result && res.result.C && res.result.C.length > 0 ? JSON.parse(JSON.stringify(res.result.C)).map((item, index) => {
            return {
              ...item,
              key: index + 1,
              title: <div onDoubleClick={() => this.detailColumnRef.onOpenModel()}>{userData && userData.language == 'EN' ? (item && item.enDescripts ? item.enDescripts : item.title) : item.title}</div>
            }
          }) : [];
          let filterArr = arr.filter(function (item) { return item.display === 'Y' });
          this.setState({ columns: filterArr, widthTotal: res.totalWidth })
        }
      }
    })
  }

  handleQuery = () => {
    this.setState({ page: 1 }, () => {
      this.getTableData();
    })
  }
  //导出
  handleExec = () => {
    this.props.form.validateFields((err, val) => {
      let obj = JSON.parse(JSON.stringify(val));
      if (err == null) {
        let data = {
          params: [{
            ...obj,
            startDate: Moment(obj.startDate).format('YYYY-MM-DD'),
            endDate: Moment(obj.endDate).format('YYYY-MM-DD'),
            allConsume: obj.allConsume ? "Y" : "N"
          }],
          pagination: [{
            pageSize:99999999,
            currentPage: 1,
          }]
        };
        $http.post('urlS', this, {
          code: "02020360",
          data: data,
          success: function (res) {
            if (res.result.filePath) {
              document.getElementById("ifile").src = window.location.protocol+"//"+window.location.host+res.result.filePath;
              message.success( '正在导出...')
            } else {
              message.error('导出失败')
            }
          },
        })
      }
    })
  };

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

  // 获取列表数据
  getTableData = () => {
    let { pageSize, page } = this.state;
    this.props.form.validateFields((err, val) => {
      let obj = JSON.parse(JSON.stringify(val));
      if (err == null) {
        // let qStkCatDr = this.props.form.getFieldValue('stkCatDr');
        let data = {
          params: [{
            ...obj,
            startDate: Moment(obj.startDate).format('YYYY-MM-DD'),
            endDate: Moment(obj.endDate).format('YYYY-MM-DD'),
            allConsume: obj.allConsume ? "Y" : "N"
          }],
          pagination: [{
            pageSize,
            currentPage: page,
          }]
        };
        $http.post('urlS', this, {
          code: "02020359",
          data: data,
          success: function (res) {
            this.child.handleLoading();
            if (+res.errorCode === 0) {
              for (var i = 0; i < res.result.rows.length; i++) {
                res.result.rows[i].key = i + 1;
              }
              this.setState({ tableData: res.result.rows, total: res.result.total })
            } else {
              this.setState({
                tableData: [], total: 0
              })
            }
          },
          error: function () {
            this.setState({
              tableData: [], total: 0
            }, () => {
              this.child.handleLoading();
            })
          }
        })
      }
    })
  }

  onDetailColumnRef = (ref) => {
    this.detailColumnRef = ref;
  }

  // 保存
  handleSave = () => {
    this.props.form.validateFields((err, val) => {
      let obj = JSON.parse(JSON.stringify(val));
      if (err == null) {
        // let qStkCatDr = this.props.form.getFieldValue('stkCatDr');
        let data = {
          params: [{
            ...obj,
            startDate: Moment(obj.startDate).format('YYYY-MM-DD'),
            endDate: Moment(obj.endDate).format('YYYY-MM-DD'),
            allConsume: obj.allConsume ? "Y" : "N"
          }],
        };
        $http.post('urlS', this, {
          code: "02020244",
          data: data,
          success: function (res) {
            if (res.errorCode == 0) {
              message.success(res.errorMessage);
              this.props.getEchoData(res.result.main.PPID);
              this.handleCancelModal();
              this.resetFields();
            }
          }
        });
      }
    })
  }

  // 获取下拉框option
  handleReturnOption = (selectData) => {
    return selectData && selectData.map((item, index) => {
      return (<Option key={index} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
    })
  }

  // 根据全院消耗change
  handleAllConsumeChange = e => {
    this.setState({ allConsume: e })
  }

  // 重置表单数据
  resetFields = () => {
    this.props.form.resetFields(); //清空所有
  }

  render() {
    let { tableData, widthTotal, columns, total, page, loading, visible, parameterSetting, allConsume, userData } = this.state;
    const { getFieldDecorator } = this.props.form;
    const formItemInput = {
      labelCol: { span: 8 },
      wrapperCol: { span: 16 }
    };

    // 组件所需参数
    const param = {
      // 表头配置
      columns: columns && columns.length > 0 ? columns : this.columns,
      // 表格数据
      data: tableData,
      // 数据总条数
      total,
      // 当前页数
      page,
      // 表格的宽度
      x: columns && columns.length > 0 ? widthTotal : 1600,
      y: 400,
      height: '450px',
      // isOnRow: true,
      // rowClassName: true,
      TableClassName: 'table-body-height',
      loading
    };
    return (
      <div className="consumption-statistics">
        <Modal
          visible={visible}
          title="消耗统计"
          onCancel={this.handleCancelModal}
          onOk={this.handleSave}
          okText="保存"
          width='85%'
          height='85%'
          className="consumption-statistics-modal"
        >
          <div>
            <Form>
            <iframe id="ifile" style={{display:'none'}}></iframe>
              <Row>
                <Col span={6}>
                  <Form.Item label="采购部门：" {...formItemInput}>
                    {getFieldDecorator('purLocID', {
                      initialValue: userData && userData.locID ? userData.locID : undefined,
                      rules: [{ required: true, message: '采购部门不能为空' }]
                    })(
                      <Select showSearch optionFilterProp="seatchprop" allowClear placeholder="请选择">
                        {this.handleReturnOption(parameterSetting && parameterSetting.loc ? parameterSetting.loc : [])}
                      </Select>
                    )}
                  </Form.Item>
                </Col>
                <Col span={6}>
                  <Form.Item label="起始日期：" {...formItemInput}>
                    {getFieldDecorator('startDate', {
                      initialValue: Moment(),
                      rules: [{ required: true, message: '起始日期不能为空' }]
                    })(
                      <DatePicker format="YYYY-MM-DD" style={{ width: '100%' }} />
                    )}
                  </Form.Item>
                </Col>
                <Col span={6}>
                  <Form.Item label="截止日期：" {...formItemInput}>
                    {getFieldDecorator('endDate', {
                      initialValue: Moment(),
                      rules: [{ required: true, message: '截止日期不能为空' }]
                    })(
                      <DatePicker format="YYYY-MM-DD" style={{ width: '100%' }} />
                    )}
                  </Form.Item>
                </Col>
                <Col span={6}>
                  <Form.Item label="库存大类：" {...formItemInput}>
                    {getFieldDecorator('stkCatID', {
                      initialValue: undefined,
                    })(
                      <Select showSearch optionFilterProp="seatchprop" allowClear placeholder="请选择">
                        {parameterSetting && parameterSetting.stkCat ? this.handleReturnOption(parameterSetting.stkCat) : []}
                      </Select>
                    )}
                  </Form.Item>
                </Col>
              </Row>
              <Row>
                <Col span={6}>
                  <Form.Item label="消耗科室：" {...formItemInput}>
                    {getFieldDecorator('useLocID', {
                      initialValue: undefined,
                      rules: [{ required: !!!allConsume, message: '消耗科室不能为空' }]
                    })(
                      <Select showSearch optionFilterProp="seatchprop" allowClear placeholder="请选择">
                        {parameterSetting && parameterSetting.loc ? this.handleReturnOption(parameterSetting.loc) : []}
                      </Select>
                    )}
                  </Form.Item>
                </Col>
                <Col span={6}>
                  <Form.Item label="用药天数：" {...formItemInput}>
                    {getFieldDecorator('useDays', {
                      initialValue: undefined,
                      rules: [{ required: true, message: '用药天数不能为空' }]
                    })(
                      <Input placeholder="请输入" type="number" className="input-number" />
                    )}
                  </Form.Item>
                </Col>
                <Col span={6}>
                  <Form.Item label="采购方式：" {...formItemInput}>
                    {getFieldDecorator('operTypeID', {
                      initialValue: undefined,
                    })(
                      <Select showSearch optionFilterProp="seatchprop" allowClear placeholder="请选择">
                        {parameterSetting && parameterSetting.operType ? this.handleReturnOption(parameterSetting.operType) : []}
                      </Select>
                    )}
                  </Form.Item>
                </Col>
                <Col span={6}>
                  <Form.Item label="库存子类：" {...formItemInput}>
                    {getFieldDecorator('stkSubCatID', {
                      initialValue: undefined,
                    })(
                      <Select showSearch optionFilterProp="seatchprop" allowClear placeholder="请选择">
                        {parameterSetting && parameterSetting.stkSubCat ? this.handleReturnOption(parameterSetting.stkSubCat) : []}
                      </Select>
                    )}
                  </Form.Item>
                </Col>
              </Row>
              <Row>
                <Col span={6}>
                  <Form.Item label="业务类型：" {...formItemInput}>
                    {getFieldDecorator('busType', {
                      initialValue: undefined,
                      rules: [{ required: !!!allConsume, message: '业务类型不能为空' }]
                    })(
                      <Select showSearch optionFilterProp="seatchprop" allowClear placeholder="请选择" mode="multiple">
                        {parameterSetting && parameterSetting.busType ? this.handleReturnOption(parameterSetting.busType) : []}
                      </Select>
                    )}
                  </Form.Item>
                </Col>
                <Col span={6}>
                  <Form.Item label="根据全院消耗：" {...formItemInput}>
                    {getFieldDecorator('allConsume', {
                      valuePropName: 'checked',
                      initialValue: false, // userInfo.CancelExecStatus === "Y" ? true : false
                    })(
                      <Switch checkedChildren="是" unCheckedChildren="否" onChange={this.handleAllConsumeChange} />
                    )}
                  </Form.Item>
                </Col>
                <Col span={6} style={{ textAlign: "right" }}>
                  <Button type="primary" onClick={this.handleQuery}>查询</Button>
                  <Button  style={{ marginLeft: '30px' }} onClick={this.handleExec}>导出</Button>
                </Col>
              </Row>
            </Form>
            <div>
              <PubilcTablePagination
                param={param}
                handelThis={this}
                onRef={this.onRef}
              // onClickRowPublic={this.onClickRowPublic}
              // setRowClassNamePublic={this.setRowClassNamePublic}
              />
            </div>
          </div>
        </Modal>
        <ColumnAuthoritysModel
          clientWidth='800px'
          compontName='ConsumptionStatistics'
          configType="C"
          onRef={this.onDetailColumnRef}
          reloadData={this.getColumns}
        />
      </div>
    );
  }
};

const ConsumptionStatisticsForm = Form.create()(ConsumptionStatistics);
export default ConsumptionStatisticsForm;