import React from "react";
import $ from "jquery/src/ajax";
import { AutoComplete, Button, Input, Spin, Table, DatePicker, Select, message, Tabs, Form, Tooltip, Modal } from "antd";
import { ChooseList } from "../../order/orderNew/chooseList"
import moment from "moment";
import ShowModalDiv from "@/showModal.jsx";
import { getStopStatus } from '@/tools';
import Cascaders from "../../../common/cascaders";
import MySuspend from '../../../common/mysuspend';
import MySuspendLog from '../../../common/logPopup/mysuspendlog';


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

//项目暂停&重启审核
const SuspendExamine = React.createClass({

  //
  getInitialState() {
    return {
      visible: false,
      pageNo: 1,
      totalPage: 0,
      searchValues: {},//查询条件
      loading: false,
      changeList: undefined,// 子组件改变的表格title数组
      pagination: {
        defaultCurrent: 1,
        defaultPageSize: 10,
        showQuickJumper: true,
        pageSize: 10,
        onChange: function (page) {
          this.setState({
            pageNo: page,
          });
          this.loadData(page);
        }.bind(this),
        showTotal: function (total) {
          return "共" + total + "条数据";
        },
      },
      columns: [
        {
          title: "时间",
          dataIndex: "createTimes",
          key: "createTimes",
          width: 80,
        },
        {
          title: "省份",
          dataIndex: "province",
          key: "province"
        },
        {
          title: "合同编号",
          dataIndex: "contractNo",
          key: "contractNo",
          render: (text, record) => {
            return (
              <Tooltip
                title={
                  <Button
                    type="primary"
                    onClick={(e) => {
                      e.stopPropagation();
                      let input = document.getElementById("copyText");
                      input.value = text;
                      input.select();
                      document.execCommand("copy");
                      message.success("复制成功");
                    }}
                  >
                    复制
                  </Button>
                }
              >
                <div>{text}</div>
              </Tooltip>
            );
          },
        },
        {
          title: "订单编号",
          dataIndex: "orderNo",
          key: "orderNo"
        },
        {
          title: "签单客户",
          dataIndex: "userName",
          key: "userName"
        },
        {
          title: "项目类型",
          dataIndex: "cname",
          key: "cname"
        },
        {
          title: "项目名称",
          dataIndex: "projectName",
          key: "projectName"
        },
        {
          title: "数量",
          dataIndex: "commodityQuantity",
          key: "commodityQuantity",
          width: 50,
        },
        {
          title: "服务类型",
          dataIndex: "serviceType",
          key: "serviceType"
        },
        {
          title: "咨询师/咨询经理",
          dataIndex: "receiverName",
          key: "receiverName"
        },
        {
          title: "项目状态",
          dataIndex: "stopStatus",
          key: "stopStatus",
          render: (value, record) => (
            <div>
              {getStopStatus(record.stopType, value)}
              <div>
                {
                  value == 0 &&
                  <Button
                    type="primary"
                    onClick={() => {
                      this.setState({
                        visible: true,
                        rowData: record,
                      })
                    }}
                  >审核</Button>
                }
              </div>
            </div>
          )
        },
        {
          title: "项目金额",
          dataIndex: "commodityPrice",
          key: "commodityPrice"
        },
        {
          title: "原因",
          dataIndex: "reason",
          key: "reason",
          width: 250,
        },
        {
          title: "日志",
          dataIndex: "rz",
          key: "rz",
          width: 90,
          render: (text, record) => (
            <div>
              <MySuspendLog id={record.id} stopType={record.stopType} />
            </div>
          )
        }
      ],
      dataSource: [],
      rowData: {},
    };
  },

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

  // 列表数据
  loadData(pageNo, pageSize) {
    const { searchValues, pagination } = this.state
    this.setState({
      loading: true,
    });
    let datas = Object.assign(searchValues, {
      pageNo: pageNo || 1,
      pageSize: pageSize || 10,
    });
    $.ajax({
      method: "get",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + "/api/admin/orderProject/selectProjectStop",
      data: datas,
      success: function (data) {
        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,
              totalPage: data.data.totalPage,
            });
          } 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)
    );
  },
  // 更改表格显示数据
  changeList(arr) {
    const newArr = [];
    this.state.columns.forEach((item) => {
      arr.forEach((val) => {
        if (val === item.title) {
          newArr.push(item);
        }
      });
    });
    this.setState({
      changeList: newArr,
    });
  },
  // 查询订单负责人列表
  followUp(e) {
    const { searchValues } = this.state;
    this.setState({
      searchValues: Object.assign(searchValues, {
        aname: 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 { searchValues, fjlist } = this.state;
    const newdataSources = JSON.stringify(fjlist) == "{}" ? [] : fjlist;
    this.setState({
      searchValues: Object.assign(searchValues, {
        receiverId: newdataSources.find((item) => item.name == value).id,
      }),
    });
  },
  // 失去焦点
  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,
    });
  },
  // 双击行
  tableRowClick(record) {
    this.setState({
      visible: true,
      rowData: record,
    })
  },
  // 搜索
  search() {
    this.setState({
      selectedRowKeys: []
    })
    this.loadData();
  },
  // 重置
  reset() {
    this.setState({
      pageNo: 1,
      searchValues: JSON.parse(JSON.stringify({})),
    }, () => {
      this.Cascaders.empty();
      this.loadData();
    })
  },


  render() {
    const { searchValues, rowData } = this.state
    const dataSources = this.state.fjlist || [];
    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} />
        <div className="content-title" style={{ marginBottom: 10 }}>
          <span style={{ fontWeight: 900, fontSize: 16 }}>审核暂停&重启项目</span>
        </div>
        <Tabs defaultActiveKey="1" onChange={this.callback} className="test">
          <TabPane tab="搜索" key="1">
            <div className="user-search" style={{ marginLeft: 10 }}>
              <Input
                placeholder="订单编号"
                style={{ width: 160 }}
                value={searchValues["orderNo"]
                  ? searchValues["orderNo"]
                  : ""}
                onChange={(e) => {
                  searchValues["orderNo"] = e.target.value;
                  this.setState({
                    searchValues: searchValues,
                  });
                }}
              />
              <Input
                placeholder="合同编号"
                style={{ width: 160 }}
                value={searchValues["contractNo"]
                  ? searchValues["contractNo"]
                  : ""}
                onChange={(e) => {
                  searchValues["contractNo"] = e.target.value;
                  this.setState({
                    searchValues: searchValues,
                  });
                }}
              />
              <Input
                placeholder="客户名称"
                style={{ width: 160 }}
                value={searchValues["userName"]
                  ? searchValues["userName"]
                  : ""}
                onChange={(e) => {
                  searchValues["userName"] = e.target.value;
                  this.setState({
                    searchValues: searchValues,
                  });
                }}
              />
              <Cascaders
                ref={node => this.Cascaders = node}
                placeholder="订单部门"
                id="id"
                name="name"
                children="list"
                height={28}
                onSel={(e) => {
                  searchValues["deps"] = JSON.stringify(e);
                  this.setState({
                    searchValues: searchValues,
                  });
                }}
              />
              <Input
                placeholder="项目名称"
                style={{ width: 160 }}
                value={searchValues["projectName"]
                  ? searchValues["projectName"]
                  : ""}
                onChange={(e) => {
                  searchValues["projectName"] = e.target.value;
                  this.setState({
                    searchValues: searchValues,
                  });
                }}
              />
              <Select
                style={{ width: 120 }}
                placeholder="项目暂停状态"
                value={searchValues["status"]
                  ? searchValues["status"]
                  : undefined}
                onChange={(e) => {
                  searchValues["status"] = e;
                  this.setState({
                    searchValues: searchValues,
                  });
                }}
              >
                <Option value="">全部</Option>
                <Option value="0">暂停待审核</Option>
                <Option value="1">重启待审核</Option>
                <Option value="2">暂停完成</Option>
                <Option value="3">重启完成</Option>
                <Option value="4">暂停已驳回</Option>
                <Option value="5">重启已驳回</Option>
              </Select>
              <AutoComplete
                dropdownMatchSelectWidth={false}
                style={{ width: 160 }}
                dataSource={options}
                placeholder="咨询师/经理"
                value={searchValues.aname || undefined}
                onChange={this.followUp.bind(this)}
                filterOption={true}
                onBlur={this.blurChange}
                onSelect={this.selectF.bind(this)}
              >
                <Input />
              </AutoComplete>
              <RangePicker
                style={{ width: 200 }}
                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 }}
                disabled={this.state.loading ? true : false}
              >
                搜索
              </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>
        </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={this.state.pagination}
              onRowDoubleClick={this.tableRowClick.bind(this)}
              size="small"
            />
          </Spin>
        </div>
        <textarea id="copyText" style={{ opacity: 0 }} />
        {
          // 项目详情
          this.state.visible &&
          <MySuspend
            isApproved={true} // 审核权限
            type="details"
            title={rowData.stopType == 0 ? "项目暂停" : "项目重启"}
            contractNo={rowData.contractNo}
            orderNo={rowData.orderNo}
            userName={rowData.userName}
            reason={rowData.reason}
            annexUrl={rowData.annexUrl}
            rowData={rowData}
            selectedRows={[{ "commodityName": rowData.projectName, "id": rowData.tid }]}
            visible={this.state.visible}
            subClose={() => {
              this.loadData(this.state.pageNo);
              this.setState({
                visible: false,
                rowData: {},
              })
            }}
          />
        }
      </div>
    );
  },
});

export default SuspendExamine;
