import React, { Component } from "react";
import { Link } from "react-router-dom";
import { getImageUrl } from "educoder";
import Tabrecru from "./component/Tabrecru";
import Tabhead from "./component/Tabhead";
import TabheadSekinds from "./component/TabheadSekinds";
import Tablereacts from "./component/Tablereacts";
import "../recrulistcss/recrulistcss.scss";
import { Tooltip, Button, Modal, message } from "antd";
import axios from "axios";
import { ThemeConsumer } from "styled-components";
import columnsConfig from "./tableColumnsConfig";
import qs from "qs";
import InfoModal from "./component/InfoModal";

const stateCof = {
  off: "下线",
  online: "上线",
  del: "删除",
};
class RecruitList extends Component {
  constructor(props) {
    super(props);
    const { tab, jobstate } = qs.parse(this.props.location.search.substr(1));
    this.state = {
      qukey: tab || "0",
      //全部表格
      dataSource: [], //数据
      page: 1, //起始页 改变页
      limit: 10, //总条数
      count: 1, //数组总长度
      loading: true, // 刷新参数
      keywords: "",
      city: "",
      jobState: jobstate || "published",
      modalVisible: false,
      stateCount: {
        published_count: 0,
        rejected_count: 0,
        drafted_count: 0,
        offline_count: 0,
      },
    };
  }
  componentDidMount() {
    // this.fetchJobsData();
  }
  fetchJobsData = () => {
    const { page, limit, qukey, keywords, city, jobState } = this.state;
    const urlcof = {
      "0": "/jobs.json",
      "1": "/users/jobs.json",
      "2": "/users/applyed_jobs.json",
    };
    const url = urlcof[qukey];
    this.setState({ loading: true });
    axios
      .get(url, {
        params: {
          q: keywords,
          per_page: limit,
          page,
          city: city === "全国" ? "" : city,
          state: jobState,
        },
      })
      .then((response) => {
        this.setState({ loading: false });
        if (response.status === 200) {
          const { state_count, data, count } = response.data;
          this.setState({
            dataSource: data,
            count,
          });
          if (state_count) {
            this.setState({ stateCount: state_count });
          }
        }
      })
      .catch((error) => {
        console.log(error);
      });
  };

  callbacks = (key) => {
    this.setState(
      {
        qukey: key,
      },
      this.fetchJobsData
    );
  };
  paginationonChange = (pageNumber) => {
    this.setState(
      {
        page: pageNumber,
      },
      this.fetchJobsData
    );
  };
  keywordCallback = (value) => {
    this.setState(
      {
        keywords: value,
      },
      this.fetchJobsData
    );
  };
  cityCallback = (city) => {
    if (!city) {
      this.fetchJobsData();
      message.error("获取定位城市失败!");
    } else {
      this.setState(
        {
          city,
        },
        this.fetchJobsData
      );
    }
  };
  jobStateCallback = (state) => {
    this.setState(
      {
        jobState: state,
      },
      this.fetchJobsData
    );
  };
  handleJobStateChange = (record, state) => {
    this.setState({
      record,
      changeState: state,
      modalVisible: true,
    });
  };
  handleJobStateSubmit = () => {
    const { record, changeState } = this.state;
    const url = `/jobs/${record.id}/change.json`;
    axios
      .put(url, {
        id: record.id,
        change: changeState,
      })
      .then((response) => {
        if (response.status === 200) {
          this.setState({ modalVisible: false });
          this.fetchJobsData();
        }
      })
      .catch((error) => {
        console.log(error);
      });
  };
  render() {
    let {
      qukey,
      dataSource,
      page,
      count,
      loading,
      limit,
      jobState,
      stateCount,
      modalVisible,
      changeState,
    } = this.state;
    let pages = 0;
    let limits = 0;
    let counts = 0;
    let loadings = true;
    pages = page;
    limits = limit;
    counts = count;
    loadings = loading;

    const DetailBtn = (record) => (
      <Button type="link">
        <Link
          to={`/recruitment/jobdetail/${record.id}`}
          style={{ color: "#4CADFF" }}
        >
          查看
        </Link>
      </Button>
    );

    const EditBtn = (record) => (
      <Button type="link">
        <Link
          to={`/recruitment/editjob/${record.id}`}
          style={{ color: "#4CADFF" }}
        >
          编辑
        </Link>
      </Button>
    );
    const OnlineBtn = (record) => (
      <Button
        type="link"
        style={{ color: "#2BB84A" }}
        onClick={() => this.handleJobStateChange(record, "online")}
      >
        上线
      </Button>
    );

    const OfflienBtn = (record) => (
      <Button
        type="link"
        style={{ color: "#2BB84A" }}
        onClick={() => this.handleJobStateChange(record, "off")}
      >
        下线
      </Button>
    );

    const DeleteBtn = (record) => (
      <Button
        type="link"
        style={{ color: "#F31010" }}
        onClick={() => this.handleJobStateChange(record, "del")}
      >
        删除
      </Button>
    );

    const defaultOperationProp = {
      title: "操作",
      dataIndex: "operation",
      key: "operation",
      align: "center",
      className: "edu-txt-center font-14",
    };
    const operationConf = {
      "0": {
        ...defaultOperationProp,
        render: (text, record) => DetailBtn(record),
      },
      "1": {
        drafted: {
          ...defaultOperationProp,
          render: (text, record) => (
            <div>
              {EditBtn(record)}
              {DeleteBtn(record)}
            </div>
          ),
        },
        published: {
          ...defaultOperationProp,
          render: (text, record) => (
            <div>
              {EditBtn(record)}
              {OfflienBtn(record)}
            </div>
          ),
        },
        rejected: {
          ...defaultOperationProp,
          render: (text, record) => (
            <div>
              {EditBtn(record)}
              {DeleteBtn(record)}
            </div>
          ),
        },
        offline: {
          ...defaultOperationProp,
          render: (text, record) => (
            <div>
              {EditBtn(record)}
              {OnlineBtn(record)}
              {DeleteBtn(record)}
            </div>
          ),
        },
      },
      "2": {
        ...defaultOperationProp,
        render: (text, record) => <div>{DetailBtn(record)}</div>,
      },
    };
    let columns;
    if (qukey && qukey !== "1") {
      columns = [...columnsConfig[qukey], operationConf[qukey]];
    } else {
      columns = [
        ...columnsConfig[qukey][jobState],
        operationConf[qukey][jobState],
      ];
    }
    return (
      <div className="newMain clearfix  ">
        <style>
          {`    ::-webkit-scrollbar {
                      width: 0px !important;
                    }
										.recruitment-head{
												width: 100%;
												height: 240px;
												background-image: url(${getImageUrl(
                          this.props.mygetHelmetapi &&
                            this.props.mygetHelmetapi.job_banner_url === null
                            ? `images/educoder/courses/courses.jpg`
                            : this.props.mygetHelmetapi &&
                                this.props.mygetHelmetapi.job_banner_url
                        )});
											  background-color: #0734B8;
												background-position: center;
												background-repeat: no-repeat;
										}

									`}
        </style>
        {this.props.mygetHelmetapi &&
        this.props.mygetHelmetapi.job_banner_url ? (
          <div className="recruitment-head pr">
            <div className="edu-txt-center pathNavLine">
              <div className="inline path-nav"></div>
            </div>
          </div>
        ) : (
          ""
        )}
        {/*内容区*/}
        <Tabrecru
          {...this.props}
          {...this.state}
          callbacks={(e) => this.callbacks(e)}
        ></Tabrecru>
        <div style={{ display: qukey === "1" ? "block" : "none" }}>
          <TabheadSekinds
            {...this.props}
            {...this.state}
            keywordCallback={this.keywordCallback}
            jobStateCallback={this.jobStateCallback}
            stateCount={stateCount}
            jobState={jobState}
          ></TabheadSekinds>
        </div>
        <div style={{ display: qukey === "1" ? "none" : "block" }}>
          <Tabhead
            {...this.props}
            {...this.state}
            keywordCallback={this.keywordCallback}
            cityCallback={this.cityCallback}
          ></Tabhead>
        </div>
        <div style={{ minHeight: 520 }}>
          {/*表格*/}
          <Tablereacts
            {...this.state}
            {...this.props}
            columns={columns} //表格数组
            dataSource={dataSource.map((item) => {
              return { ...item, key: item.id };
            })} //数据
            page={pages} //起始页 改变页
            limit={limits} //总条数
            count={counts} //数组总长度
            loading={loadings} // 刷新参数
            paginationonChange={(e) => this.paginationonChange(e)}
          ></Tablereacts>
        </div>

        <InfoModal
          visible={modalVisible}
          onCancel={() => this.setState({ modalVisible: false })}
          content={`确定要${stateCof[changeState]}该职位?`}
          footer={
            <div style={{ textAlign: "center", padding: "10px 0px" }}>
              <Button
                onClick={() => {
                  this.setState({ modalVisible: false });
                }}
                style={{
                  backgroundColor: "#cccccc",
                  color: "#ffffff",
                }}
              >
                取消
              </Button>
              <Button
                type="primary"
                onClick={() => {
                  this.handleJobStateSubmit();
                }}
              >
                确定
              </Button>
            </div>
          }
        ></InfoModal>
      </div>
    );
  }
}

export default RecruitList;
