import React from "react";
import $ from "jquery/src/ajax";
import {
  Button, Input, Spin, Table, DatePicker, TreeSelect,
  Form, message, Tabs, Modal, Select, AutoComplete,
} from "antd";
import { ShowModal } from "@/tools";
import moment from "moment";
import "./index.less";
import ShowModalDiv from "@/showModal.jsx";
import { ChooseList } from "../../order/orderNew/chooseList"
import InvestmentLog from "../../../common/logPopup/investmentlog";
import LaunchInvest from "../../amiba/component/launchinvest"; // 发起投资

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

// 投资列表
const Investment = React.createClass({

  //
  getInitialState() {
    return {
      searchValues: {}, // 列表筛选条件
      loading: false, //加载动画
      changeList: undefined, // 更改后的表格显示数据
      dataSource: [], // 列表数据
      pagination: {
        defaultCurrent: 1,
        defaultPageSize: 10,
        showQuickJumper: true,
        pageSize: 10,
        onChange: function (page) {
          this.loadData(page);
        }.bind(this),
        showTotal: function (total) {
          return "共" + total + "条数据";
        },
      },
      columns: [
        {
          title: "投资时间",
          dataIndex: "createTimes",
          key: "createTimes",
          width: "10%",
        },
        {
          title: "金额（万元）",
          dataIndex: "amount",
          key: "amount",
          width: "10%",
        },
        {
          title: "累计金额（万元）",
          dataIndex: "countAmount",
          key: "countAmount",
          width: "10%",
        },
        {
          title: "投资方",
          dataIndex: "initiateName",
          key: "initiateName",
          width: "10%",
        },
        {
          title: "接收方",
          dataIndex: "acceptName",
          key: "acceptName",
          width: "10%",
        },
        {
          title: "操作人",
          dataIndex: "operator",
          key: "operator",
          width: "10%",
        },
        {
          title: "状态",
          dataIndex: "status",
          key: "status",
          width: "8%",
          render: (text, record) =>
            <span style={{ color: text === 3 && "red" }}>
              {["草稿", "待审核", "同意", "驳回"][text]}
            </span>
        },
        {
          title: "备注",
          dataIndex: "comment",
          key: "comment",
          width: "20%",
        },
        {
          title: "操作",
          dataIndex: "operate",
          key: "operate",
          width: "12%",
          render: (text, record) =>
            <div>
              {
                record.status === 1 && this.props.type == "cwzy" &&
                <Button
                  type="primary"
                  onClick={() => {
                    this.setState({
                      checkVisible: true,
                      rowData: record
                    })
                  }}
                >审核</Button>
              }
              {
                record.status === 3 && this.props.type == "my" &&
                <Button
                  type="primary"
                  onClick={() => {
                    this.setState({
                      visible: "invest",
                      rowData: record
                    })
                  }}
                >重新发起</Button>
              }
              <InvestmentLog id={record.id} />
            </div >
        }
      ],
      checkVisible: false,
      rowData: {},
      visible: "",
    };
  },


  componentWillMount() {
    const { searchValues } = this.state
    this.getList();
    if (this.props.type == "cwzy") {
      searchValues.status = 1
      this.setState({
        searchValues,
      }, () => {
        this.loadData();
      })
    } else {
      this.loadData();
    }
  },


  // 导出当前列表
  exportAll() {
    const { searchValues } = this.state
    message.config({
      duration: 20,
    });
    let loading = message.loading("下载中...");
    this.setState({
      exportPendingLoading: true,
    });
    let data = Object.assign(searchValues, {
      pageNo: 1,
      pageSize: 9999,
    });
    $.ajax({
      method: "get",
      dataType: "json",
      crossDomain: false,
      url: "/api/admin/orderProject/selectProjectStop/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({
          exportPendingLoading: 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,
    });
  },
  // 搜索
  search() {
    this.loadData();
  },
  // 重置
  reset() {
    this.setState({
      auto: "",
      searchValues: JSON.parse(JSON.stringify({})),
    }, () => {
      this.loadData();
    })
  },
  // 列表接口
  loadData(pageNo) {
    const { searchValues, pagination } = this.state;
    this.setState({
      loading: true,
    });
    let datas = Object.assign(searchValues, {
      pageNo: pageNo || 1,
      pageSize: pagination.pageSize,
      roleType: this.props.type == "cwzy" ? 1
        : this.props.type == "my" && 0, //0 巴主发起列表 1财务审核列表
    });
    $.ajax({
      method: "get",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + "/api/admin/amb/Invest/InvestList",
      data: datas,
      success: function (data) {
        ShowModal(this);
        this.setState({
          loading: false,
        });
        if (data.error && data.error.length === 0) {
          if (data.data.list) {
            pagination.current = data.data.pageNo;
            pagination.total = data.data.totalCount;
            if (data.data && data.data.list && !data.data.list.length) {
              pagination.current = 0;
              pagination.total = 0;
            }
            this.setState({
              dataSource: data.data.list,
              pagination: this.state.pagination,
              pageNo: data.data.pageNo,
            });
          } else {
            this.setState({
              dataSource: data.data,
              pagination: false,
            });
          }
        } else {
          message.warning(data.error[0].message);
        }
      }.bind(this),
    }).always(
      function () {
        this.setState({
          loading: false,
        });
      }.bind(this)
    );
  },
  // 双击行
  rowClick(record) {
    if (this.props.type == "cwzy") {
      this.setState({
        checkVisible: true,
        rowData: record
      })
    }
  },
  // 审核
  examineTransfer(status) {
    if (!this.state.emReason) {
      message.warning("请填写审核说明~");
      return;
    }
    if (!this.state.emReason.replace(/\s+/g, '')) {
      message.warning("请填写审核说明~");
      return;
    }
    this.setState({
      loading: true,
    });
    $.ajax({
      method: "POST",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + "/api/admin/amb/Invest/examineTransfer",
      data: {
        id: this.state.rowData.id,
        comment: this.state.emReason,
        status,
      },
    }).done(
      function (data) {
        if (!data.error.length) {
          this.setState({
            loading: false,
          })
          message.success("审核成功！");
          this.loadData()
          this.setState({
            checkVisible: false,
            emReason: "",
          })
        } else {
          message.warning(data.error[0].message);
        }
      }.bind(this)
    );
  },
  // 关闭重新发起
  onCancel(e) {
    if (e) {
      this.loadData()
    }
    this.setState({
      visible: "",
    })
  },
  // 树状默认数据处理
  handleTreeData(treeData) {
    let nodeDta = [];
    treeData.map(item => {
      let treeObj = {};
      treeObj.key = item.id
      treeObj.id = item.id
      treeObj.value = item.id
      treeObj.label = item.name
      treeObj.title = item.name
      treeObj.lvl = item.lvl
      treeObj.parentId = item.parentId
      item.list ? treeObj.children = this.handleTreeData(item.list) : null;
      nodeDta.push(treeObj)
    })
    return nodeDta
  },
  // 巴筛选数据
  getList() {
    this.setState({
      loading: true,
    });
    $.ajax({
      method: "get",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + "/api/admin/amb/selectAll",
      success: function (data) {
        this.setState({
          loading: false,
        });
        if (data.error && data.error.length === 0) {
          let menuList = data.data
          this.setState({
            level1Data: menuList ? this.handleTreeData(menuList) : []
          });
        } else {
          message.warning(data.error[0].message);
        }
      }.bind(this),
    }).always(
      function () {
        this.setState({
          loading: false,
        });
      }.bind(this)
    );
  },

  supervisor(e) {
    $.ajax({
      method: "get",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + "/api/admin/customer/listAdminByName",
      data: {
        adminName: e,
        status: "0",
      },
      success: function (data) {
        if (data.error && data.error.length === 0) {
          this.setState({
            customerArr: data.data,
          });
        } else {
          message.warning(data.error[0].message);
        }
      }.bind(this),
    }).always(function () { }.bind(this));
  },

  httpChange(e) {
    if (e.length >= 1) {
      this.supervisor(e);
    }
    this.setState({
      auto: e,
    })
  },

  blurChange(e) {
    let contactLists = this.state.customerArr || [];
    if (e) {
      let id = ""
      contactLists.map(function (item) {
        if (item.name == e.toString()) {
          id = item.id;
        }
      });
      this.setState({
        searchValues: Object.assign(this.state.searchValues, {
          operator: id,
        }),
      })
    }
  },

  selectAuto(value, options) {
    this.setState({
      auto: value,
    })
  },

  render() {
    const { searchValues, rowData, level1Data } = this.state
    const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 14 },
    };
    const dataSources = this.state.customerArr || [];
    const options = dataSources.map((group) => (
      <Select.Option key={group.id} value={group.name}>
        {group.name}
      </Select.Option>
    ));
    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 }}>
            {this.props.type == "cwzy" ? "投资审核" : "我的投资"}
          </span>
        </div>
        <Tabs defaultActiveKey="1" onChange={this.callback}>
          <TabPane tab="搜索" key="1">
            <div className="user-search" style={{ marginLeft: 10 }}>
              <TreeSelect
                style={{ width: 200 }}
                value={searchValues.initiateAmbId}
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                treeData={level1Data}
                placeholder="投资方"
                showSearch
                treeNodeFilterProp="title"
                onChange={(e) => {
                  searchValues["initiateAmbId"] = e;
                  this.setState({
                    searchValues: searchValues,
                  });
                }}
              />
              <TreeSelect
                style={{ width: 200 }}
                value={searchValues.acceptAmbId}
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                treeData={level1Data}
                placeholder="接收方"
                showSearch
                treeNodeFilterProp="title"
                onChange={(e) => {
                  searchValues["acceptAmbId"] = e;
                  this.setState({
                    searchValues: searchValues,
                  });
                }}
              />
              <AutoComplete
                className="certain-category-search"
                dropdownClassName="certain-category-search-dropdown"
                dropdownMatchSelectWidth={false}
                style={{ width: "200px" }}
                dataSource={options}
                placeholder="操作投资人"
                value={this.state.auto}
                onChange={this.httpChange}
                filterOption={true}
                onBlur={this.blurChange}
                onSelect={this.selectAuto}
              >
                <Input />
              </AutoComplete>
              <Select
                placeholder="选择状态"
                style={{ width: 200 }}
                value={searchValues.status}
                onChange={e => {
                  this.setState({
                    searchValues: Object.assign(searchValues, {
                      status: e,
                    }),
                  })
                }}
              >
                <Select.Option value={1}>待审核</Select.Option>
                <Select.Option value={2}>已同意</Select.Option>
                <Select.Option value={3}>已驳回</Select.Option>
              </Select>
              <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
                onClick={this.reset}
              >重置</Button>
            </div>
          </TabPane>
          <TabPane tab="更改表格显示数据" key="2">
            <div style={{ marginLeft: 10 }}>
              <ChooseList
                columns={this.state.columns}
                changeFn={this.changeList}
                changeList={this.state.changeList}
                top={55}
                margin={11}
              />
            </div>
          </TabPane>
          <TabPane tab="导出Excel" key="3">
            <Button
              type="primary"
              style={{ margin: "11px 0px 10px 10px" }}
              onClick={this.exportAll}
            >
              导出当前列表
            </Button>
          </TabPane>
        </Tabs>
        <div className="patent-table">
          <Spin spinning={this.state.loading}>
            <Table
              bordered
              size="middle"
              columns={
                this.state.changeList == undefined
                  ? this.state.columns
                  : this.state.changeList
              }
              dataSource={this.state.dataSource}
              pagination={this.state.pagination}
              onRowDoubleClick={this.rowClick}
            />
          </Spin>
        </div>
        {
          //审核弹窗
          this.state.checkVisible &&
          <Modal
            visible={this.state.checkVisible}
            width="33%"
            title=""
            footer=""
            onCancel={() => { this.setState({ checkVisible: false }) }}
          >
            <Spin spinning={this.state.loading}>
              <div>
                <div style={{ textAlign: "center", fontSize: "20px", marginBottom: 40 }}>拨款</div>
                <Form>
                  <FormItem
                    className="half-item"
                    {...formItemLayout}
                    label="投资方"
                  >
                    <span>{rowData.initiateName}</span>
                  </FormItem>
                  <FormItem
                    className="half-item"
                    {...formItemLayout}
                    label="接受方"
                  >
                    <span>{rowData.acceptName}</span>
                  </FormItem>
                  <FormItem
                    className="half-item"
                    {...formItemLayout}
                    label="投资款(万元)"
                  >
                    <span>{rowData.amount}</span>
                  </FormItem>
                  <FormItem
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 16 }}
                    label="投资备注"
                  >
                    <span>{rowData.comment}</span>
                  </FormItem>
                  <FormItem
                    className="half-item"
                    {...formItemLayout}
                    label="发起人"
                  >
                    <span>{rowData.operator}</span>
                  </FormItem>
                  <FormItem
                    className="half-item"
                    {...formItemLayout}
                    label="发起时间"
                  >
                    <span>{rowData.createTimes}</span>
                  </FormItem>
                  {
                    rowData.status === 1 && this.props.type == "cwzy" &&
                    <div>
                      <FormItem
                        labelCol={{ span: 4 }}
                        wrapperCol={{ span: 16 }}
                        label={
                          <span>
                            <strong style={{ color: "#f00" }}>*</strong>
                            备注
                          </span>
                        }
                      >
                        <Input
                          type="textarea"
                          rows={4}
                          placeholder="请填写审核说明"
                          value={this.state.emReason}
                          onChange={(e) => {
                            this.setState({ emReason: e.target.value });
                          }}
                        />
                      </FormItem>
                      <FormItem wrapperCol={{ span: 12, offset: 7 }}>
                        <Button
                          type="primary"
                          onClick={() => { this.examineTransfer(2) }}
                          style={{ marginRight: 20 }}
                        >
                          确定拨款
                        </Button>
                        <Button
                          type="primary"
                          onClick={() => { this.examineTransfer(3) }}
                          style={{ marginRight: 20 }}
                        >
                          驳回
                        </Button>
                        <Button
                          type="default"
                          onClick={() => { this.setState({ checkVisible: false }) }}
                        >
                          取消
                        </Button>
                      </FormItem>
                    </div>
                  }
                </Form>
              </div>
            </Spin>
          </Modal>
        }

        {
          // 重新发起投资
          this.state.visible == "invest" &&
          <LaunchInvest
            myAmbId={this.state.rowData.initiateAmbId} //发起方的阿米巴id
            details={this.state.rowData}
            visible={this.state.visible}
            onCancel={this.onCancel.bind(this)}
          />
        }
      </div>
    );
  },
});

export default Investment;
