import React from "react";
import $ from "jquery/src/ajax";
import moment from "moment";
import "./public.less";
import {
  Form,
  Button,
  Input,
  Select,
  Spin,
  Table,
  message,
  Modal,
  Upload,
  DatePicker,
  Icon,
  Tabs,
  Popconfirm,
  Tag
} from "antd";
import {
  getProjectStatus,
  getProvinceA,
  getInvoiceStatus,
  getprovince,
  getStatus,
  getPeople,
  splitUrl
} from "@/tools";
import { ChooseList } from "../../../../component/manageCenter/order/orderNew/chooseList";
import "./huiKuan.less"

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

const HuiKuan = React.createClass({
  loadData(pageNo) {
    this.state.data = [];
    this.setState({
      loading: true
    });
    $.ajax({
      method: "get",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + "/api/admin/receivables/listReceivables",
      data: {
        pageNo: pageNo || 1,
        pageSize: this.state.pagination.pageSize,
        // 订单状态 判断是否重复
        status: this.state.statusSearch,
        // 订单编号
        orderNo: this.state.orderNoSearch,
        // 合同编号
        contractNo: this.state.contractSearch,
        // 付款方
        corporateName: this.state.corporateName,
        // 营销员名字
        adminName: this.state.adminName,
        // 客户名称
        nickname: this.state.nickname,
        // 订单所属部门id
        orderDepId: this.state.orderDepId,
        // 管理员部门id
        adminDepId: this.state.adminDepId
      },
      success: function(data) {
        let theArr = [];
        if (!data.data || !data.data.pagination.list) {
          if (data.error && data.error.length) {
            message.warning(data.error[0].message);
          }
        } else {
          for (let i = 0; i < data.data.pagination.list.length; i++) {
            let thisdata = data.data.pagination.list[i];
            theArr.push({
              key: thisdata.id,
              status: thisdata.status,
              orderNo: thisdata.orderNo,
              contractNo: thisdata.contractNo,
              corporateName: thisdata.corporateName,
              nickname: thisdata.nickname,
              totalAmount: thisdata.totalAmount,
              depName: thisdata.depName,
              amount: thisdata.amount,
              receivablesTimes: thisdata.receivablesTimes,
              createTimes: thisdata.createTimes,
              remarks: thisdata.remarks
            });
          }
        }
        this.state.pagination.current = data.data.pagination.pageNo;
        this.state.pagination.total = data.data.pagination.totalCount;
        if (
          data.data &&
          data.data.pagination.list &&
          !data.data.pagination.list.length
        ) {
          this.state.pagination.current = 0;
          this.state.pagination.total = 0;
        }
        this.setState({
          totalPage: data.data.pagination.totalPage,
          dataSource: theArr,
          pagination: this.state.pagination,
          totalAmount: data.data.count.totalAmount,
          amount: data.data.count.amount
        });

          console.log(this.state.dataSource);

        
      }.bind(this)
    }).always(
      function() {
        this.setState({
          loading: false
        });
      }.bind(this)
    );
  },

  departmentList() {
    this.setState({
      loading: true
    });
    $.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() {
        this.setState({
          loading: false
        });
      }.bind(this)
    );
  },

  getInitialState() {
    return {
      visible: false,
      selectedRowKeys: [], // Check here to configure the default column
      loading: false,
      searchMore: true,
      assignVisible: false,
      releaseDate: [],
      totalPage: 0,
      boHuivisible: false,
      selectedRowKeys: [],
      selectedRows: [],
      // 弹出层数据
      modalData: {},
      // userName: "",
      contractNo: "",
      loading: false,
      reason: "",
      foo: 0,
      // 子组件改变的表格title数组
      changeList: undefined,
      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: "contractNo",
          key: "contractNo"
          // fixed: "left"
        },
        {
          title: "订单编号",
          dataIndex: "orderNo",
          key: "orderNo"
        },
        {
          title: "客户名称",
          dataIndex: "corporateName",
          key: "corporateName"
        },
        {
          title: "合同额",
          dataIndex: "totalAmount",
          key: "totalAmount"
        },
        {
          title: "本次回款（万元）",
          dataIndex: "amount",
          key: "amount"
        },
        {
          title: "回款时间",
          dataIndex: "receivablesTimes",
          key: "receivablesTimes"
        },
        {
          title: "状态",
          dataIndex: "status",
          key: "status",
          render: status => {
            let str = "";
            let color = "";
            if (status == 0) {
              str = "正常";
              color = "#87d068";
            } else if(status == 1) {
              str = "重复";
              color = "#f50";
            }else {
              str = "异常"
              color = "#000";
            }
            return <Tag color={color}>{str}</Tag>;
          }
        },
        {
          title: "批量导入时间",
          dataIndex: "createTimes",
          key: "createTimes"
        },
        {
          title: "备注",
          dataIndex: "remarks",
          key: "remarks"
        }
      ],
      columnsDate: [
        {
          title: "编号",
          dataIndex: "id",
          key: "id"
        },
        {
          title: "订单编号",
          dataIndex: "orderno",
          key: "orderno"
        },
        {
          title: "开票金额(万元)",
          dataIndex: "amount",
          key: "amount"
        },
        {
          title: "申请时间",
          dataIndex: "createTime",
          key: "createTime"
        },
        {
          title: "开票状态",
          dataIndex: "status",
          key: "status",
          render: text => {
            return getInvoiceStatus(text);
          }
        }
      ],
      dataSource: [],

      upLoadFlag: false,
      upLoad: {
        name: "file",
        action: "https://www.mocky.io/v2/5cc8019d300000980a055e76",
        headers: {
          authorization: "authorization-text"
        },
        onChange: info => {
          if (info.file.status !== "uploading") {
            console.log(info.file, info.fileList);
          }
          if (info.file.status === "done") {
            message.success(`${info.file.name} 文件上传成功`);

            this.state.upLoadFlag = true;

            this.setState({
              upLoadFlag: this.state.upLoadFlag,
              dataSource
            });
          } else if (info.file.status === "error") {
            message.error(`${info.file.name} 文件上传失败`);

            this.state.upLoadFlag = false;
            this.setState({
              upLoadFlag: this.state.upLoadFlag
            });
          }
          console.log(info);
        }
        // beforeUpload: (file,fileList) => {
        //   if (fileList.length = 1) {
        //     this.state.upLoadFlag = true;
        //     this.setState({
        //       upLoadFlag: this.state.upLoadFlag
        //     });
        //   } else {
        //     this.state.upLoadFlag = false;
        //     this.setState({
        //       upLoadFlag: this.state.upLoadFlag
        //     });
        //   }
        // }
      }
    };
  },

  search() {
    this.loadData();
  },

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

    $("#rcDialogTitle0").on("click", function() {
      alert(123);
      console.log(123);
    });
  },
  reset() {
    this.state.nameSearch = "";
    this.state.releaseDate = [];
    this.state.orderNoSearch = "";
    this.state.userName = "";
    this.state.departmenttList = [];
    this.state.orderUserName = "";
    this.state.principalList = [];
    this.state.payFrom = "";
    this.state.orderStatus = [];
    // this.loadData();
  },

  changeList(arr) {
    const newArr = [];
    this.state.columns.forEach(item => {
      arr.forEach(val => {
        if (val === item.title) {
          newArr.push(item);
        }
      });
    });
    this.setState({
      changeList: newArr
    });
  },
  onSelectChange(selectedRowKeys) {
    console.log("selectedRowKeys changed: ", selectedRowKeys);
    this.setState({ selectedRowKeys });
  },
  showModal() {
    this.setState({
      visible: true
    });
    this.state.dataSource.forEach((item) => {
      if(item.key == this.state.selectedRowKeys[0]) {
        this.setState({
          modalData: item
        })
      }
    })
  },

  handleOk() {
    this.setState({ loading: true });
    setTimeout(() => {
      this.setState({ loading: false, visible: false });
    }, 3000);
  },

  handleCancel() {
    this.setState({ visible: false });
  },
  callback(key) {
  console.log(key);
  },
  delChecked() {
    console.log("被删除列表",this.state.selectedRowKeys);
    // this.loadData()
  },
  delAllChecked() {
    console.log("删除全部");
    // this.loadData()
    // console.log("aaa", $(".ant-modal-content"));
    
    
  },
  mergeAll() {
    console.log("合并全部");
    // this.loadData()
    
  },
  render() {
    const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 14 }
    };
    var departmentArr = this.state.departmentArr || [];
    const { loading, selectedRowKeys, visible } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
      hideDefaultSelections: true
    };
    var departmentArr = this.state.departmentArr || [];
    return (
      <div className="user-content" style={{ position: "relative" }}>
        <div className="content-title" style={{ marginBottom: 10 }}>
          <span style={{ fontWeight: 900, fontSize: 16 }}>回款</span>
        </div>

        <Tabs defaultActiveKey="1" onChange={this.callback}>
          <TabPane tab="搜索" key="1">
            <div className="user-search" style={{ marginLeft: 10 }}>
              <Input
                placeholder="合同编号"
                value={this.state.nameSearch}
                onChange={e => {
                  this.setState({ nameSearch: e.target.value });
                }}
              />
              <Input
                placeholder="订单编号"
                value={this.state.orderNoSearch}
                onChange={e => {
                  this.setState({ orderNoSearch: e.target.value });
                }}
              />
              <Input
                placeholder="客户名称"
                value={this.state.userName}
                onChange={e => {
                  this.setState({ userName: e.target.value });
                }}
              />
              <Select
                placeholder="状态"
                style={{ width: 150, marginRight: 10 }}
                value={this.state.orderStatus}
                onChange={e => {
                  this.setState({ orderStatus: e });
                  console.log("状态",e);
                  
                }}
              >
                <Select.Option key={0}>正常</Select.Option>
                <Select.Option key={1}>重复</Select.Option>
                <Select.Option key={2}>异常</Select.Option>
              </Select>

              <Input
                placeholder="订单负责人"
                value={this.state.orderUserName}
                onChange={e => {
                  this.setState({ userName: e.target.value });
                }}
              />

              <Select
                placeholder="负责人所属部门"
                style={{ width: 150, marginRight: 10 }}
                value={this.state.principalList}
                onChange={e => {
                  this.setState({ principalList: e });
                }}
              >
                {departmentArr.map(function(item) {
                  return (
                    <Select.Option key={item.id}>{item.name}</Select.Option>
                  );
                })}
              </Select>

              <Input
                placeholder="付款方"
                value={this.state.payFrom}
                onChange={e => {
                  this.setState({ payFrom: e.target.value });
                }}
              />
              <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}
                display={"inline-block"}
                style={{ marginBottom: 17 }}
              />
            </div>
          </TabPane>
          <TabPane tab="操作" key="3">
            <div
              class={123}
              style={{
                position: "relative",
                top: 10,
                left: 10,
                // zIndex: 99,
                // left: 400,
                // transform: "translateX(-50%)",
                display:"inline-block"
              }}
            >
              <Upload {...this.state.upLoad}>
                <Button
                  type="primary"
                  disabled={this.state.dataSource.length != 0}
                >
                  <Icon type="upload" />
                  导入回款列表
                </Button>
              </Upload>
            </div>

            <Button
              type="primary"
              style={{ marginBottom: 20, marginLeft: 15 }}
              disabled={this.state.selectedRowKeys.length == 1 ? false : true}
              onClick={this.showModal}
            >
              修改单条数据
            </Button>

            <Popconfirm
              placement="top"
              title={"您确定要删除选中项的回款信息吗？删除后，不可以修改！"}
              onConfirm={this.delChecked}
              okText="确定"
              cancelText="取消"
            >
              <Button
                primary
                type="danger"
                style={{ marginBottom: 20, marginLeft: 15 }}
                disabled={this.state.selectedRowKeys.length > 0 ? false : true}
              >
                删除选中项
              </Button>
            </Popconfirm>

            <Popconfirm
              placement="top"
              title={"您确定要删除全部的回款信息吗？删除后，不可以修改！"}
              onConfirm={this.delAllChecked}
              okText="确定"
              cancelText="取消"
            >
              <Button
                type="danger"
                style={{ marginBottom: 20, marginLeft: 15 }}
              >
                删除全部
              </Button>
            </Popconfirm>

            <Popconfirm
              placement="top"
              title={"您确定要合并全部的回款信息吗？合并后，不可以修改！"}
              onConfirm={this.mergeAll}
              okText="确定"
              cancelText="取消"
            >
              <Button
                type="danger"
                style={{ marginBottom: 20, marginLeft: 15 }}
                disabled={this.state.dataSource.length != 0}
              >
                确认合并回款
              </Button>
            </Popconfirm>
          </TabPane>
        </Tabs>

        <div className="patent-table" style={{ position: "relative" }}>
          <Spin spinning={this.state.loading}>
            <Table
              columns={
                this.state.changeList == undefined
                  ? this.state.columns
                  : this.state.changeList
              }
              //   scroll={{ x: 1500, y: 0 }}
              dataSource={this.state.dataSource}
              pagination={this.state.pagination}
              rowSelection={rowSelection}
              bordered
            />
          </Spin>
        </div>

        <Modal
          width={800}
          visible={visible}
          title="收款记录"
          onOk={this.handleOk}
          onCancel={this.handleCancel}
          footer={[
            <Button key="back" onClick={this.handleCancel}>
              取消
            </Button>,
            <Button
              key="submit"
              type="primary"
              loading={loading}
              onClick={this.handleOk}
            >
              保存
            </Button>
          ]}
        >
          <p style={{ marginBottom: 10 }}>
            合同编号：{this.state.modalData.name}
          </p>
          <p style={{ marginBottom: 10 }}>
            订单编号：{this.state.modalData.name}
          </p>
          <p style={{ marginBottom: 10 }}>
            客户名称：{this.state.modalData.name}
          </p>
          <p style={{ marginBottom: 10 }}>
            合同额（万元）：
            <Input
              style={{ width: "auto" }}
              value={this.state.modalData.hetong}
              onChange={e => {
                let val = e.target.value;
                this.state.modalData.hetong = val;
                this.setState({ modalData: this.state.modalData });
              }}
            />
          </p>
          <p style={{ marginBottom: 10 }}>
            本次回款（万元）：
            <Input
              style={{ width: "auto" }}
              value={this.state.modalData.benci}
              onChange={e => {
                let val = e.target.value;
                this.state.modalData.benci = val;
                this.setState({ modalData: this.state.modalData });
              }}
            />
          </p>
          <p style={{ marginBottom: 10 }}>
            回款时间：
            <DatePicker
              showTime
              placeholder="选择回款时间"
              value={moment(this.state.modalData.huiTime, "YYYY-MM-DD")}
              onChange={(v, e) => {
                this.state.modalData.huiTime = e;
                console.log(e);

                this.setState({ modalData: this.state.modalData });
              }}
              onOk={() => {}}
            />
          </p>
          <p style={{ marginBottom: 10 }}>
            批量导入时间：{this.state.modalData.daoTime}
          </p>
          <p style={{ marginBottom: 10 }}>
            <span style={{ display: "inline-block", marginBottom: 20 }}>
              备注：
            </span>
            <TextArea
              style={{ width: "70%" }}
              value={this.state.modalData.remake}
              onChange={e => {
                this.state.modalData.remake = e.target.value;
                console.log(e);

                this.setState({ modalData: this.state.modalData });
              }}
              placeholder="请输入备注信息"
              autosize={{ minRows: 3, maxRows: 5 }}
            />
          </p>
        </Modal>
      </div>
    );
  }
});

export default HuiKuan;
