import React from "react";
import $ from "jquery/src/ajax";
import moment from "moment";
import {
  Button,
  Form,
  Input,
  Spin,
  Table,
  Select,
  message,
  Tabs,
  DatePicker,
} from "antd";
import { ChooseList } from "../../order/orderNew/chooseList";
import { ShowModal, commonAdd } from "../../../tools"
import ShowModalDiv from "@/showModal.jsx";

const FormItem = Form.Item;
const { RangePicker } = DatePicker;
const { TabPane } = Tabs;

const AccountReview = React.createClass({

  getInitialState() {
    return {
      searchValues: {}, // 列表筛选条件
      loading: false, //加载动画
      changeList: undefined, // 更改后的表格显示数据
      dataSource: [], // 列表数据
      departmentArr: [],
      columns: [
        {
          title: "报销人员",
          dataIndex: "aname",
          key: "aname",
        },
        {
          title: "报销/借支/抵扣次数",
          dataIndex: "bx",
          key: "bx",
          render: (text, record) => {
            return (
              <div>
                <div>{text + "/" + record.jz + "/" + record.dk}</div>
              </div>
            );
          },
        },
        {
          title: "报销/借支/抵扣金额（元)",
          dataIndex: "bxAmount",
          key: "bxAmount",
          render: (text, record) => {
            return (
              <div>{text + "/" + record.jzAmount + "/" + record.dkAmount}</div>
            );
          },
        },
        {
          title: "报销总金额（元)",
          dataIndex: "totalAmount",
          key: "totalAmount",
        },
        {
          title: "固定费用总金额（元）",
          dataIndex: "gdfyAmount",
          key: "gdfyAmount",
        },

        {
          title: "报销至订单金额（元）",
          dataIndex: "bxddAmount",
          key: "bxddAmount",
        },
        {
          title: "未审核次数",
          dataIndex: "wshs",
          key: "wshs",
        },
        {
          title: "驳回次数",
          dataIndex: "bhs",
          key: "bhs",
        },
      ],
    };
  },

  componentWillMount() {
    this.departmentList();
    this.loadData();
  },

  // 列表接口
  loadData() {
    const { searchValues } = this.state;
    this.setState({
      loading: true,
    });
    let datas = searchValues;
    $.ajax({
      method: "get",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + "/api/admin/expenseAccount/statistics",
      data: datas,
      success: function (data) {
        ShowModal(this);
        this.setState({
          loading: false,
        });
        if (data.error && data.error.length === 0) {
          if (data.data.list) {
            this.setState({
              dataSource: data.data.list,
            });
          } else {
            this.setState({
              dataSource: data.data,
            });
          }
        } else {
          message.warning(data.error[0].message);
        }
      }.bind(this),
    }).always(
      function () {
        this.setState({
          loading: false,
        });
      }.bind(this)
    );
  },

  // 部门信息
  departmentList() {
    $.ajax({
      method: "get",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + "/api/admin/organization/selectSuperId",
      data: {},
      success: function (data) {
        let thedata = data.data;
        let theArr = [];
        if (!thedata) {
          if (data.error && data.error.length) {
            message.warning(data.error[0].message);
          }
        } else {
          thedata.map(function (item, index) {
            theArr.push({
              key: index,
              name: item.name,
              id: item.id
            });
          });
        }
        this.setState({
          departmentArr: theArr
        });
      }.bind(this)
    }).always(
      function () {

      }.bind(this)
    );
  },


  // 搜索
  search() {
    this.loadData();
  },

  // 重置
  reset() {
    this.setState({
      searchValues: JSON.parse(JSON.stringify({})),
    }, () => {
      this.loadData();
    })
  },

  // 清除缓存
  evict() {
    this.setState({
      loading: true,
    });
    $.ajax({
      method: "get",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + "/api/admin/expenseAccount/statistics/evict",
      data: {},
      success: function (data) {
        ShowModal(this);
        this.setState({
          loading: false,
        });
        if (data.error && data.error.length === 0) {
          message.success("清除成功！")
        } else {
          message.warning(data.error[0].message);
        }
      }.bind(this),
    }).always(
      function () {
        this.setState({
          loading: false,
        });
      }.bind(this)
    );
  },

  // 导出
  export() {
    this.setState({
      exportExecLoading: true
    })
    let loading = message.loading('加载中...');
    let data = this.state.searchValues;
    $.ajax({
      method: "get",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + "/api/admin/expenseAccount/statistics/export",
      data,
      success: function (data) {
        if (data.error.length === 0) {
          this.download(data.data);
        } else {
          message.warning(data.error[0].message);
        }
      }.bind(this),
    }).always(function () {
      loading();
      this.setState({
        exportExecLoading: false
      })
    }.bind(this));
  },

  // 下载
  download(fileName) {
    window.location.href = globalConfig.context + "/open/download?fileName=" + fileName
  },

  changeList(arr) {
    const newArr = [];
    this.state.columns.forEach((item) => {
      arr.forEach((val) => {
        if (val === item.title) {
          newArr.push(item);
        }
      });
    });
    this.setState({
      changeList: newArr,
    });
  },


  render() {
    const { searchValues, } = this.state

    return (
      <div className="user-content">
        <ShowModalDiv ShowModal={this.state.showModal} onClose={() => { this.setState({ showModal: false }) }} />
        <div className="content-title" style={{ marginBottom: 10 }}>
          <span style={{ fontWeight: 900, fontSize: 16 }}>费用统计</span>
        </div>
        <Tabs defaultActiveKey="2" className="test">
          <TabPane tab="更改表格显示数据" key="1">
            <div style={{ marginLeft: 10 }}>
              <ChooseList
                columns={this.state.columns}
                changeFn={this.changeList}
                changeList={this.state.changeList}
                top={55}
                margin={11}
              />
            </div>
          </TabPane>
          <TabPane tab="搜索" key="2">
            <div className="user-search" style={{ marginLeft: 10 }}>

              <Input
                placeholder="请输入报销人员"
                value={searchValues["name"]
                  ? searchValues["name"]
                  : ""}
                onChange={(e) => {
                  searchValues["name"] = e.target.value;
                  this.setState({
                    searchValues: searchValues,
                  });
                }}
              />
              <Select
                placeholder="所属部门"
                style={{ width: 200, marginRight: 10 }}
                value={searchValues["depId"]
                  ? searchValues["depId"]
                  : undefined}
                onChange={e => {
                  searchValues["depId"] = e;
                  this.setState({
                    searchValues: searchValues,
                  });
                }}
              >
                {this.state.departmentArr.map(function (item) {
                  return <Select.Option key={item.id}>{item.name}</Select.Option>;
                })}
              </Select>

              <span>报销时间：</span>
              <RangePicker
                style={{ width: 300 }}
                value={[
                  searchValues.startTime ? moment(searchValues.startTime) : null,
                  searchValues.endTime ? moment(searchValues.endTime) : null,
                ]}
                onChange={(data, dataString) => {
                  this.setState({
                    searchValues: Object.assign(searchValues, {
                      startTime: dataString[0],
                      endTime: dataString[1],
                    }),
                  });
                }}
              />
              <Button
                type="primary"
                onClick={this.search}
                style={{ marginLeft: 10 }}
              >
                搜索
              </Button>
              <Button style={{ marginLeft: 10 }} onClick={this.reset}>重置</Button>
              <Button
                type="primary"
                onClick={this.evict}
                style={{ marginLeft: 10 }}
              >
                清除缓存
              </Button>
            </div>
          </TabPane>
          <TabPane tab="导出Excel" key="3">
            <Button type="primary" style={{ float: "left", margin: 10 }} onClick={this.export}>
              导出excel
            </Button>
          </TabPane>
        </Tabs>
        <div className="patent-table">
          <Spin spinning={this.state.loading}>
            <Table
              bordered
              columns={
                this.state.changeList == undefined
                  ? this.state.columns
                  : this.state.changeList
              }
              dataSource={this.state.dataSource}
              pagination={false}
              size="small"
            />
          </Spin>
        </div>
      </div>
    );
  },
});

export default AccountReview;
