import React from 'react';
import ReactDom from 'react-dom';
import ajax from 'jquery/src/ajax/xhr.js';
import $ from 'jquery/src/ajax';
import {
  Form, Icon, Button, Input, Select, AutoComplete, Spin, Table,
  message, DatePicker, Modal, TreeSelect, Popconfirm, Tabs
} from 'antd';
import Newuser from "./newUser.jsx"
import { ShowModal } from "@/tools";
import { ChooseList } from "../../order/orderNew/chooseList";

const { TabPane } = Tabs
const Team = Form.create()(React.createClass({
  getInitialState() {
    return {
      info: {},
      searchValues: {}, // 列表筛选条件
      loading: false, //加载动画
      changeList: undefined, // 更改后的表格显示数据
      departmentArr: [], // 部门
      dataSource: [], // 列表数据
      teamList: [], // 上级
      fjlist: [],
      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: 'name',
          key: 'name',
        },
        {
          title: '队长',
          dataIndex: 'adminName',
          key: 'adminName',
        },
        {
          title: '等级',
          dataIndex: 'lvl',
          key: 'lvl',
          render: (text, record) => {
            return (
              <div>
                {["", "一级", "二级", "三级"][text]}
              </div>
            )
          }
        },
        {
          title: '部门',
          dataIndex: 'depName',
          key: 'depName',
        },
        {
          title: '上级团队',
          dataIndex: 'superName',
          key: 'superName',
        },
        {
          title: '状态',
          dataIndex: 'status',
          key: 'status',
          render: (text, record) => {
            return (
              <div>
                {["正常", "解散"][text]}
              </div>
            )
          }
        },

      ],
      visible: "",
    };
  },

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

  // 列表接口
  loadData(pageNo) {
    const { searchValues, pagination } = this.state;
    this.setState({
      loading: true,
    });
    let datas = Object.assign(searchValues, {
      pageNo: pageNo || 1,
      pageSize: pagination.pageSize,
    });
    $.ajax({
      method: "get",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + "/api/admin/salesTeam/pageList",
      data: datas,
      success: function (data) {
        ShowModal(this);
        this.setState({
          loading: false,
        });
        let theArr = [];
        if (data.error && data.error.length === 0) {
          if (data.data) {
            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 {
          message.warning(data.error[0].message);
        }
      }.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);
          };
          thedata = {};
        } else {
          thedata.map(function (item, index) {
            theArr.push({
              key: index,
              name: item.name,
              id: item.id,
              depNo: item.depNo
            })
          })
        }
        this.setState({
          departmentArr: theArr,
        })
      }.bind(this),
    }).always(function () {
      this.setState({
        loading: false
      });
    }.bind(this));
  },

  // 团队
  salesTeam(lvl) {
    this.setState({
      loading: true
    });
    $.ajax({
      method: "get",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + "/api/admin/salesTeam/list",
      data: {
        lvl: lvl - 1
      },
      success: function (data) {
        let thedata = data.data;
        let theArr = [];
        if (!thedata) {
          if (data.error && data.error.length) {
            message.warning(data.error[0].message);
          };
          thedata = {};
        } else {
          thedata.map(function (item, index) {
            theArr.push({
              name: item.name,
              id: item.id,
            })
          })
        }
        this.setState({
          teamList: theArr,
        })
      }.bind(this),
    }).always(function () {
      this.setState({
        loading: false
      });
    }.bind(this));
  },

  followUp(e) {
    const { info } = this.state;
    this.setState({
      info: Object.assign(info, {
        adminName: e,
      }),
    });
    $.ajax({
      method: "get",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + "/api/admin/customer/listAdminByName",
      data: {
        adminName: e,
      },
      success: function (data) {
        let thedata = data.data;
        if (!thedata) {
          if (data.error && data.error.length) {
            message.warning(data.error[0].message);
          }
          thedata = {};
        }
        this.setState({
          fjlist: thedata,
        });
      }.bind(this),
    }).always(
      function () {
        this.setState({
          loading: false,
        });
      }.bind(this)
    );
  },

  selectF(value) {
    const { info, fjlist } = this.state;
    const newdataSources = JSON.stringify(fjlist) == "{}" ? [] : fjlist;
    info["aid"] = newdataSources.find((item) => item.name == value).id;
    this.setState({
      info
    });
  },

  tableRowClick(record, index) {
    this.salesTeam(record.lvl)
    this.setState({
      visible: "edit",
      info: record,
    })
  },

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

  reset() {
    this.setState({
      searchValues: {}
    }, () => {
      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
    });
  },

  // 保存
  handleOk() {
    const { info } = this.state
    if (!info.name) {
      message.warn("团队名称不能为空！")
      return
    }
    if (!info.adminName) {
      message.warn("队长姓名不能为空！")
      return
    }
    if (!info.lvl) {
      message.warn("请选择等级！")
      return
    }
    if (!info.depId) {
      message.warn("请选择部门！")
      return
    }
    // if (!info.superId) {
    //   message.warn("请选择上级团队！")
    //   return
    // }
    if (!info.status && info.status != 0) {
      message.warn("请选择状态！")
      return
    }
    let obj = {
      id: info.id,
      name: info.name,
      aid: info.aid,
      lvl: info.lvl,
      depId: info.depId,
      superId: info.superId,
      status: info.status,
    }
    this.setState({
      loading: true
    });
    $.ajax({
      method: "POST",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + (!info.id ? "/api/admin/salesTeam/add" : "/api/admin/salesTeam/update"),
      data: obj
    }).done(function (data) {
      this.setState({
        loading: false
      });
      if (!data.error.length) {
        message.success('保存成功！');
        this.handleCancel();
        this.loadData();
      } else {
        message.warning(data.error[0].message);
      }
    }.bind(this));
  },

  handleCancel() {
    this.setState({
      visible: "",
      info: {},
    })
  },

  render() {
    const { searchValues, departmentArr, teamList, info } = this.state
    const FormItem = Form.Item
    const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 14 },
    };
    const newdataSources = this.state.fjlist || [];
    const newoptions = newdataSources.map((group) => (
      <Select.Option key={group.id} value={group.name}>
        {group.name}
      </Select.Option>
    ));
    return (
      <div className="user-content">
        <div className="content-title">
          <Tabs defaultActiveKey="1" onChange={this.callback} className="test">
            <TabPane tab="搜索" key="1">
              <div className="user-search" style={{ paddingBottom: 10 }}>
                <Input
                  placeholder="用户姓名"
                  style={{ width: "180px" }}
                  value={searchValues["userName"]
                    ? searchValues["userName"]
                    : ""}
                  onChange={e => {
                    searchValues["userName"] = e.target.value;
                    this.setState({
                      searchValues: searchValues,
                    });
                  }}
                />
                <Select
                  placeholder="部门"
                  style={{ width: 180 }}
                  value={searchValues["depId"]
                    ? searchValues["depId"]
                    : undefined}
                  onChange={e => {
                    searchValues["depId"] = e;
                    this.setState({
                      searchValues,
                    });
                  }}
                >
                  {departmentArr.map(function (item) {
                    return (
                      <Select.Option key={item.id}>{item.name}</Select.Option>
                    );
                  })}
                </Select>
                <Select
                  placeholder="状态"
                  style={{ width: 180 }}
                  value={searchValues["status"]
                    ? searchValues["status"]
                    : undefined}
                  onChange={e => {
                    searchValues["status"] = e;
                    this.setState({
                      searchValues,
                    });
                  }}
                >
                  <Select.Option value="0">正常</Select.Option>
                  <Select.Option value="1">解散</Select.Option>
                </Select>
                <Button
                  type="primary"
                  onClick={this.search}
                  style={{ margin: "0 10px" }}
                >搜索</Button>
                <Button onClick={this.reset}>重置</Button>
                <Button
                  type="primary"
                  style={{
                    marginBottom: '15px',
                    position: "absolute",
                    right: 0,
                  }}
                  onClick={() => {
                    this.setState({
                      visible: "add"
                    })
                  }}
                >
                  新增团队
                </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>
          </Tabs>
          <div className="patent-table">
            <Spin spinning={this.state.loading}>
              <Table
                bordered
                columns={
                  this.state.changeList
                    ? this.state.changeList
                    : this.state.columns
                }
                style={{
                  cursor: 'pointer',
                }}
                dataSource={this.state.dataSource}
                pagination={this.state.pagination}
                onRowDoubleClick={this.tableRowClick}
              />
            </Spin>
          </div>

          <Modal
            title={this.state.visible == "add"
              ? "新建团队" : this.state.visible == "edit"
                ? "编辑团队" : "????"}
            width={610}
            visible={this.state.visible != ""}
            footer={null}
            onCancel={this.handleCancel}
          >
            <Form
              layout="horizontal"
            >
              <Spin spinning={this.state.loading}>
                <div className="clearfix">
                  <FormItem
                    className="half-middle"
                    {...formItemLayout}
                    label="团队名称"
                  >
                    <Input
                      placeholder="团队名称"
                      value={info["name"] ? info["name"] : undefined}
                      style={{ width: "230px" }}
                      onChange={(e) => {
                        info["name"] = e.target.value;
                        this.setState({ info });
                      }}
                      required="required"
                    />
                  </FormItem>

                  <FormItem
                    className="half-middle"
                    {...formItemLayout}
                    label="队长"
                  >
                    <AutoComplete
                      className="certain-category-search"
                      dropdownClassName="certain-category-search-dropdown"
                      dropdownMatchSelectWidth={false}
                      style={{ width: "230px" }}
                      dataSource={newoptions}
                      placeholder="队长姓名"
                      value={info["adminName"] || undefined}
                      onChange={this.followUp.bind(this)}
                      filterOption={true}
                      onSelect={this.selectF.bind(this)}
                    >
                      <Input />
                    </AutoComplete>
                  </FormItem>

                  <FormItem
                    className="half-middle"
                    {...formItemLayout}
                    label="等级"
                  >
                    <Select
                      placeholder="选择等级"
                      style={{ width: "230px" }}
                      value={info["lvl"] ? info["lvl"] : undefined}
                      onChange={(e) => {
                        info["lvl"] = e;
                        info["superId"] = null;
                        this.setState({ info });
                        this.salesTeam(e)
                      }}
                    >
                      {[
                        { key: "一级", value: 1 },
                        { key: "二级", value: 2 },
                        { key: "三级", value: 3 }].map(function (item) {
                          return (
                            <Select.Option key={item.value} value={item.value}>
                              {item.key}
                            </Select.Option>
                          );
                        })}
                    </Select>
                  </FormItem>

                  <FormItem
                    className="half-middle"
                    {...formItemLayout}
                    label="所属部门"
                  >
                    <Select
                      placeholder="部门"
                      style={{ width: 230 }}
                      value={info["depId"]
                        ? info["depId"]
                        : undefined}
                      onChange={e => {
                        info["depId"] = e;
                        this.setState({
                          info,
                        });
                      }}
                    >
                      {departmentArr.map(function (item) {
                        return (
                          <Select.Option key={item.id}>{item.name}</Select.Option>
                        );
                      })}
                    </Select>
                  </FormItem>

                  <FormItem
                    className="half-middle"
                    {...formItemLayout}
                    label="上级团队"
                  >
                    <Select
                      placeholder="上级团队"
                      style={{ width: 230 }}
                      value={info["superId"]
                        ? info["superId"]
                        : undefined}
                      onChange={e => {
                        info["superId"] = e;
                        this.setState({
                          info,
                        });
                      }}
                    >
                      {teamList.map(function (item) {
                        return (
                          <Select.Option key={item.id} value={item.id}>{item.name}</Select.Option>
                        );
                      })}
                    </Select>
                  </FormItem>

                  <FormItem
                    className="half-middle"
                    {...formItemLayout}
                    label="状态"
                  >
                    <Select
                      placeholder="选择状态"
                      style={{ width: "230px" }}
                      value={info["status"]}
                      onChange={(e) => {
                        info["status"] = e;
                        this.setState({
                          info,
                        });
                      }}
                    >
                      <Select.Option value={0}>正常</Select.Option>
                      <Select.Option value={1}>解散</Select.Option>
                    </Select>
                  </FormItem>
                </div>

                <FormItem className="half-middle">
                  <Button
                    className="set-submit"
                    type="primary"
                    style={{ marginLeft: "150px" }}
                    onClick={this.handleOk}
                  >
                    保存
                  </Button>
                  <Button
                    className="set-submit"
                    type="ghost"
                    onClick={this.handleCancel}
                  >
                    取消
                  </Button>
                </FormItem>
              </Spin>
            </Form>
          </Modal>

        </div>
      </div>
    );
  }
}));

export default Team;
