import React from "react";
import $ from "jquery/src/ajax";
import moment from "moment";
import {
  Button,
  Form,
  Input,
  Spin,
  Table,
  Select,
  message,
  Tabs,
  DatePicker,
  AutoComplete,
  Modal,
  Tooltip,
  Tag,
} from "antd";
import { ChooseList } from "../../../order/orderNew/chooseList";
import { ShowModal, } from "@/tools.js"
import { accountType, accountStatus } from "@/dataDic";
import ZhuanjiaoDetail from "@/zhuanjiaoDetail.jsx";
import IntentionDetail from "./intentionDetail/intentionDetail";
import ShowModalDiv from "@/showModal.jsx";
import FollowDetail from "./followDetail"
import './limit.less';

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

const LimitedProject = React.createClass({

  getInitialState() {
    return {
      searchValues: {
        type: ''
      }, // 列表筛选条件
      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: "name",
          key: "name",
          width: 300,
          render: (text, record) => {
            return (
              <span>
                <span>{text}</span>
              </span>
            );
          },
        },
        {
          title: "限定项目名称",
          dataIndex: "projectName",
          key: "projectName",
          render: (text, record) => {
            return (
              <div>
                {text}
              </div>
            );
          },
        },
        {
          title: "项目状态",
          dataIndex: "type",
          key: "type",
          render: (text, record) => {
            return (
              <div>
                {['公共', '私有', '签单'][text]}
              </div>
            );
          },
        },
        {
          title: "客户所属",
          dataIndex: "userAdmin",
          key: "userAdmin",
          render: (text, record) => {
            return (
              <div>
                {text}
              </div>
            );
          },
        },
        {
          title: "项目所属",
          dataIndex: "adminName",
          key: "adminName",
          render: (text, record) => {
            return (
              <div>
                {text}
              </div>
            );
          },
        },
        // {
        //   title: "项目初始时间",
        //   dataIndex: "lockTime",
        //   key: "lockTime",
        //   render: (text, record) => {
        //     return (
        //       <div>
        //         {text}
        //       </div>
        //     );
        //   },
        // },
        {
          title: "剩余私有天数",
          dataIndex: "privateDays",
          key: "privateDays",
          render: (text, record) => {
            return (
              <div>
                {record.type == 1
                  ? text : record.type == 2
                    ? record.signDays : ""}
              </div>
            );
          },
        },
        {
          title: "最新跟进时间",
          dataIndex: "lockTime",
          key: "lockTime",
          render: (text, record) => {
            return (
              <div>
                {text}
              </div>
            );
          },
        },
        {
          title: "操作",
          dataIndex: "op",
          key: "op",
          render: (text, record) => {
            return (
              <div>
                <Button
                  style={{ marginLeft: 10 }}
                  type="primary"
                  onClick={(e) => {
                    e.stopPropagation();
                    let obj = {
                      id: record.id
                    }
                    this.setState({
                      visitModuls: true,
                      followData: obj,
                      RowData: record,
                    })
                  }}
                >
                  跟进限定项目
                </Button>
              </div>
            );
          },
        },
      ],
      customerArr: [],
      selectedRowKeys: [],
      zhuanjiaoVisible: false,
      categoryArr: [],
      followData:{}
    };
  },

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

  // 列表接口
  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/restrict/Project/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
            };
            for (var i = 0; i < data.data.list.length; i++) {
              let thisdata = data.data.list[i];
              let diqu =
                (thisdata.province == null ? "" : thisdata.province) +
                (thisdata.city == null ? "" : "-" + thisdata.city) +
                (thisdata.area == null ? "" : "-" + thisdata.area);
              thisdata.opId = thisdata.id;
              thisdata.id = thisdata.uid;
              thisdata.locationProvince = diqu;
              theArr.push(thisdata);
            }
            this.setState({
              dataSource: theArr,
              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)
    );
  },
  // 搜索
  search() {
    this.loadData();
  },
  // 重置
  reset() {
    this.setState({
      searchValues: {
        type: ''
      },
    }, () => {
      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,
    });
  },

  supervisor(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({
          customerArr: thedata,
        });
      }.bind(this),
    }).always(
      function () {
        this.setState({
          loading: false,
        });
      }.bind(this)
    );
  },

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

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

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

  showConfirm() {
    let _this = this;
    Modal.confirm({
      title: "提示",
      content: (
        <span style={{ color: "red" }}>
          确定要转交以下项目吗？
          {this.state.selectedRows.map((value, index) => (
            <div key={index} style={{ marginTop: "5px", color: "#000" }}>
              {value.projectName}
            </div>
          ))}
        </span>
      ),
      onOk() {
        _this.changeAssigner(1)
      },
      onCancel() { },
    });
  },

  showConfirms() {
    let _this = this;
    Modal.confirm({
      title: "您确定将以下项目移至公共项目吗？",
      content: (
        <span style={{ color: "red" }}>
          移除后，以下项目将被别人领取！
          {this.state.selectedRows.map((value, index) => (
            <div key={index} style={{ marginTop: "5px", color: "#000" }}>
              {value.projectName}
            </div>
          ))}
        </span>
      ),
      onOk() {
        _this.changeAssigner(0);
      },
      onCancel() { },
    });
  },

  changeAssigner(type) {
    const _this = this;
    if (type == 1 && !this.state.theTypes) {
      message.warning("请输入转交人姓名");
      return
    }
    let changeIds = "";
    for (let idx = 0; idx < this.state.selectedRows.length; idx++) {
      let rowItem = this.state.selectedRows[idx];
      if (rowItem.opId) {
        changeIds =
          this.state.selectedRows.length - 1 === idx
            ? changeIds + rowItem.opId
            : changeIds + rowItem.opId + ",";
      }
    }
    let loading = message.loading("加载中...");
    $.ajax({
      method: "post",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + "/api/restrict/Project/update",
      data: {
        id: changeIds,
        type,
        takeAid: type == 1 ? this.state.theTypes : undefined,
      },
    }).done(
      function (data) {
        loading();
        this.setState({
          selList: [],
        })
        if (!data.error.length) {
          this.setState({
            auto: "",
            loading: false,
            selectedRowKeys: [],
          });
          if (data.data == 1) {
            message.success(type == 1 ? "转交成功！" : "移除成功！");
            _this.loadData();
          } else {
            data.data.forEach(function (e) { message.warning(e) })
          }
        } else {
          message.warning(data.error[0].message);
        }
      }.bind(this)
    );
  },

  zhuanjiaoDetail(record) {
    this.setState({
      zhuanjiaoVisible: true,
      zhuanjiaoId: record.id,
    });
  },

  zhuanjiaoDetailCancel() {
    this.setState({
      zhuanjiaoVisible: false,
    });
  },

  tableRowClick(record, index) {
    this.state.visitModul = false;
    this.setState({
      // selectedRowKeys: [],
      modalVisible: true,
      basicState: true,
      contactState: true,
      modalName: record.name,
      RowData: record,
    });
  },

  closeDesc(e, s) {
    this.state.basicState = e;
    this.state.visitModul = e;
    this.state.modalVisible = e;
    this.state.visitModuls = e;
    this.state.showDesc = e;
    this.setState({
      tabsKey: "",
    });
    if (s) {
      this.loadData(this.state.ispage);
    }
  },
  //品类数据获取
  category() {
    $.ajax({
      method: "get",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + "/api/admin/Varieties/getSuperList",
      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({
              value: item.id,
              key: item.cname,
            });
          });
        }
        this.setState({
          categoryArr: theArr,
        });
      }.bind(this),
    });
  },
  //查看跟进记录列表
  loadVisit(pageNo) {
    this.setState({
      loading: true
    });
    $.ajax({
      method: "get",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + '/api/admin/customer/listFollowHistory',
      data: {
        pageNo: pageNo || 1,
        pageSize: this.state.paginations.pageSize,
        uid: this.state.RowData.id, //名称1
      },
      success: function (data) {
        let theArr = [];
        if (data.error.length || data.data.list == "") {
          if (data.error && data.error.length) {
            message.warning(data.error[0].message);
          };
        } else {
          for (let i = 0; i < data.data.list.length; i++) {
            let thisdata = data.data.list[i];
            theArr.push(thisdata);
          };
          this.state.paginations.current = data.data.pageNo;
          this.state.paginations.total = data.data.totalCount;
          this.setState({
            ispage: data.data.pageNo
          })
        };
        if (data.data.list && !data.data.list.length) {
          this.state.paginations.current = 0;
          this.state.paginations.total = 0;
        };
        this.setState({
          visitArrList: theArr,
          paginations: this.state.paginations
        });
      }.bind(this),
    }).always(function () {
      this.setState({
        loading: false
      });
    }.bind(this));
  },

  render() {
    const { searchValues, } = this.state
    const rowSelection = {
      hideDefaultSelections: true,
      selectedRowKeys: this.state.selectedRowKeys,
      onChange: (selectedRowKeys, selectedRows) => {
        this.setState({
          modalVisible: false,
          selectedRows: selectedRows,
          selectedRowKeys: selectedRowKeys,
        });
      },
      onSelect: (recordt, selected, selectedRows) => {
        this.setState({
          modalVisible: false,
          recordt: recordt.opId,
        });
      },
    };
    const hasSelected = this.state.selectedRowKeys.length > 0;
    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 }}>限定项目</span>
        </div>
        <Tabs defaultActiveKey="1" className="test">
          <TabPane tab="搜索" key="1">
            <div className="user-search" style={{ marginLeft: 10 }}>
              <Input
                placeholder="客户名称"
                value={searchValues["userName"]
                  ? searchValues["userName"]
                  : ""}
                onChange={(e) => {
                  searchValues["userName"] = e.target.value;
                  this.setState({
                    searchValues: searchValues,
                  });
                }}
              />
              <Input
                placeholder="请输入限定项目全称"
                value={searchValues["projectName"]
                  ? searchValues["projectName"]
                  : ""}
                onChange={(e) => {
                  searchValues["projectName"] = e.target.value;
                  this.setState({
                    searchValues: searchValues,
                  });
                }}
              />
              <Select
                style={{ width: 140 }}
                placeholder=""
                value={searchValues["type"]}
                onChange={(e) => {
                  searchValues["type"] = e;
                  this.setState({
                    searchValues: searchValues,
                  });
                }}
              >
                <Option value="">全部</Option>
                <Option value="1">私有</Option>
                <Option value="2">已签</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={{ margin: "0 10px" }}
              >搜索</Button>
              <Button onClick={this.reset}>重置</Button>
            </div>
          </TabPane>
          <TabPane tab="操作" key="2">
            <div className="user-search" style={{ marginLeft: 10 }}>
              <AutoComplete
                className="certain-category-search"
                dropdownClassName="certain-category-search-dropdown"
                dropdownMatchSelectWidth={false}
                style={{ width: "120px" }}
                dataSource={options}
                placeholder="输入转交人姓名"
                value={this.state.auto}
                onChange={this.httpChange}
                filterOption={true}
                onBlur={this.blurChange}
                onSelect={this.selectAuto}
                disabled={!hasSelected}
              >
                <Input />
              </AutoComplete>
              <Button
                type="primary"
                onClick={(e) => {
                  e.stopPropagation();
                  this.showConfirm();
                }}
                disabled={!hasSelected}
                style={{ marginRight: 10 }}
              >
                转交
              </Button>
              <Button
                style={{ marginLeft: 10 }}
                onClick={(e) => {
                  e.stopPropagation();
                  this.showConfirms();
                }}
                type="primary"
                disabled={!hasSelected}
              >
                移除项目
              </Button>
              <Button
                style={{ marginLeft: 10 }}
                onClick={(e) => {
                  e.stopPropagation();
                  this.zhuanjiaoDetail(this.state.selectedRows[0]);
                }}
                type="primary"
                disabled={!hasSelected || this.state.selectedRows.length > 1}
              >
                项目日志
              </Button>
            </div>
          </TabPane>
          <TabPane tab="更改表格显示数据" key="3">
            <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
              size="middle"
              bordered
              columns={
                this.state.changeList == undefined
                  ? this.state.columns
                  : this.state.changeList
              }
              dataSource={this.state.dataSource}
              rowSelection={rowSelection}
              pagination={this.state.pagination}
              onRowDoubleClick={this.tableRowClick}
            />
          </Spin>
        </div>
        {
          this.state.zhuanjiaoVisible &&
          <ZhuanjiaoDetail
            cancel={this.zhuanjiaoDetailCancel}
            visible={this.state.zhuanjiaoVisible}
            id={this.state.zhuanjiaoId}
          />
        }
        {
          this.state.modalVisible &&
          <IntentionDetail
            isLimit={true}
            isCustomerAdmin={true}
            tabsKey={this.state.tabsKey}
            categoryArr={this.state.categoryArr}
            detailApi={'/api/admin/customer/findOrganizationCustomerDetail'}
            IntentionData={this.state.RowData}
            modalVisible={this.state.modalVisible}
            name={this.state.modalName}
            closeDesc={this.closeDesc}
            basicState={this.state.basicState}
            contactState={this.state.contactState}
          />
        }
        {
          <FollowDetail
            isLimit={true}
            details={this.state.RowData}
            categoryArr={this.state.categoryArr}
            followData={this.state.followData}
            visitModul={this.state.visitModuls}
            closeDesc={this.closeDesc}
            loadData={this.loadVisit}
          />
        }
      </div>
    );
  },
});

export default LimitedProject;
