import React, { Component } from "react";
import {
  Dropdown,
  Icon,
  Menu,
  Pagination,
  Modal,
  Input,
  Popconfirm,
  Form,
  Spin,
  Button,
  Table,
} from "antd";
import "../Order/order.css";
import "./setting.scss";
import NoneData from "../Nodata";
import { SketchPicker } from "react-color";
import reactCSS from "reactcss";
import axios from "axios";
import {WhiteBack} from '../Component/layout';

class NewTags extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: undefined,
      limit: 15,
      page: 1,
      order_name: undefined,
      order_type: undefined,
      //新建标签区域是否显示 none 隐藏 block 显示
      display: "none",
      //调色盘颜色
      displayColorPicker: false,
      color: {
        r: "241",
        g: "112",
        b: "19",
        a: "1",
      },
      textcolor: "#F17013",
      isShow: false,
      newcolor: "",
      name: "",
      description: "",
      id: "",
      modelname: "",
      isSpin: true,
    };
  }
  componentDidUpdate=(prevPros)=>{
    if(prevPros && this.props && !this.props.checkIfLogin()){
      this.props.history.push("/403")
      return
    }
  }
  componentDidMount = () => {
    this.getList();
  };

  getList = (page, order_name, order_type) => {
    this.setState({
      isSpin:true
    })
    const { projectsId , owner } = this.props.match.params;
    const { limit } = this.state;
    const url = `/${owner}/${projectsId}/labels.json`;
    axios
      .get(url, {
        params: {
          page,
          limit,
          order_name,
          order_type,
        },
      })
      .then((result) => {
        if (result) {
          this.setState({
            data: result.data,
            isSpin:false
          });
        }
      })
      .catch((error) => {
        console.log(error);
      });
  };

  createtagpost = () => {
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { projectsId ,owner } = this.props.match.params;
        const url = `/${owner}/${projectsId}/labels.json`;
        axios
          .post(url, {
            ...values,
            project_id: projectsId,
            color: this.state.textcolor,
          })
          .then((result) => {
            if (result) {
              this.props.form.setFieldsValue({
                name: "",
                description: "",
              });
              this.setState({
                color: {
                  r: "241",
                  g: "112",
                  b: "19",
                  a: "1",
                },
                textcolor: "#F17013",
                display: "none",
              });
              this.getList();
            }
          })
          .catch((error) => {
            console.log(error);
          });
      }
    });
  };

  ChangePage = (page) => {
    this.setState({
      page,
    });

    this.getList(page);
  };

  // 排序
  arrayList = (e) => {
    this.setState({
      order_name: e.key,
      order_type: e.item.props.value,
    });

    this.getList(1, e.key, e.item.props.value);
  };

  handleClick = () => {
    this.setState({ displayColorPicker: !this.state.displayColorPicker });
  };

  handleClose = () => {
    this.setState({ displayColorPicker: false });
  };

  handleChange = (color) => {
    this.setState({
      color: color.rgb,
      textcolor: color.hex,
      newcolor: color.hex,
    });
  };

  //控制新建标签页是否显示
  newshow = () => {
    this.setState({
      display: "block",
    });
  };
  newclose = () => {
    this.setState({
      display: "none",
    });
  };

  handleok = () => {
    this.updatetag();
  };
  updatetag = () => {
    const { projectsId ,owner } = this.props.match.params;
    let id = this.state.id;
    const url = `/${owner}/${projectsId}/labels/${id}.json`;
    let name = this.state.name;
    let description = this.state.description;
    let modalcolor = this.state.newcolor;
    axios
      .put(url, {
        project_id: projectsId,
        id: id,
        name: name,
        description: description,
        color: modalcolor,
      })
      .then((result) => {
        if (result) {
          this.setState({
            isShow: false,
          });
          this.getList();
        }
      })
      .catch((error) => {
        console.log(error);
      });
  };

  deletetag = (id) => {
    const { projectsId , owner } = this.props.match.params;
    const url = `/${owner}/${projectsId}/labels/${id}.json`;
    axios
      .delete(url, {
        data: {
          project_id: projectsId,
          id: id,
        },
      })
      .then((result) => {
        if (result) {
          this.getList();
        }
      })
      .catch((error) => {
        console.log(error);
      });
  };

  handleCancel = () => {
    this.setState({
      isShow: false,
    });
  };

  changmodelname = (e) => {
    this.setState({
      name: e.target.value,
    });
  };
  changdescription = (e) => {
    this.setState({
      description: e.target.value,
    });
  };

  editshow = (arr) => {
    this.setState({
      isShow: true,
      newcolor: arr.color,
      name: arr.name,
      description: arr.description,
      id: arr.id,
    });
  };

  render() {
    const { data, limit, page, isSpin } = this.state;
    const { getFieldDecorator } = this.props.form;

    const menu = (
      <Menu onClick={this.arrayList}>
        <Menu.Item key={"created_at"} value="desc">
          按创建时间降序排序
        </Menu.Item>
        <Menu.Item key={"created_at"} value="asc">
          按创建时间升序排序
        </Menu.Item>
        <Menu.Item key={"issues_count"} value="desc">
          按issue个数降序排序
        </Menu.Item>
        <Menu.Item key={"issues_count"} value="asc">
          按issue个数升序排序
        </Menu.Item>
      </Menu>
    );
    const styles = reactCSS({
      default: {
        color: {
          width: "20px",
          height: "20px",
          borderRadius: "2px",
          background: `rgba(${this.state.color.r}, ${this.state.color.g}, ${this.state.color.b}, ${this.state.color.a})`,
        },
        swatch: {
          padding: "5px",
          background: "#fff",
          borderRadius: "1px",
          width: "100px",
          marginTop: "5px",
          height: "28px",
          boxShadow: "0 0 0 1px rgba(0,0,0,.1)",
          display: "flex",
          cursor: "pointer",
        },
        popover: {
          position: "absolute",
          zIndex: "2",
        },
        cover: {
          position: "fixed",
          top: "0px",
          right: "0px",
          bottom: "0px",
          left: "0px",
        },
        modalcolor: {
          width: "20px",
          height: "20px",
          borderRadius: "2px",
          background: this.state.newcolor,
        },
      },
    });
    const columns = [
      {
        title: "颜色代码",
        width: "20%",
        dataIndex: "color",
        render: (text, item) => (
          <span className="grid-item">
            <span
              style={{ backgroundColor: `${item.color}` }}
              className="tagColor"
            ></span>
            <span className="ml15">{item.name}</span>
          </span>
        ),
      },
      {
        title: "描述",
        width: "30%",
        dataIndex: "description",
        render: (text) => <span>{text}</span>,
      },
      {
        title: "问题数量",
        width: "30%",
        dataIndex: "issues_count",
        render: (text) => <span>{text}个开启的任务</span>,
      },
      {
        title: "操作",
        width: "20%",
        dataIndex: "action",
        render: (text, item) => (
          <span style={{ justifyContent: "center" }}>
            <a
              onClick={() => this.editshow(item)}
              className="topWrapper_success_btn fr"
            >
              编辑
            </a>
            <Popconfirm
              placement="bottom"
              title={"删除标签会将其从所有引用中删除。继续？"}
              okText="是"
              cancelText="否"
              onConfirm={() => this.deletetag(item.id)}
            >
              <a className="a_btn delete_btn fr">删除</a>
            </Popconfirm>
          </span>
        ),
      },
    ];

    const Paginations = (
      <React.Fragment>
        {data && data.issue_tags_count > limit ? (
          <div className="mt30 mb50 edu-txt-center">
            <Pagination
              simple
              defaultCurrent={page}
              total={data && data.issue_tags_count}
              pageSize={limit}
              onChange={this.ChangePage}
            ></Pagination>
          </div>
        ) : (
          ""
        )}
      </React.Fragment>
    );

    const renderList = () => {
      if (data && data.issue_tags && data.issue_tags.length > 0) {
        return (
          <div>
            <div className="topWrapper" style={{borderBottom:"1px solid #eee"}}>
              <span>共{data && data.issue_tags_count}个标签</span>
              <ul className="topWrapper_select">
                <li>
                  <Dropdown
                    className="topWrapperSelect"
                    overlay={menu}
                    trigger={["click"]}
                    placement="bottomCenter"
                  >
                    <span>
                      标签
                      <Icon type="caret-down" className="ml5" />
                    </span>
                  </Dropdown>
                </li>
              </ul>
            </div>
            <div>
              <Table
                className="setTables"
                showHeader={false}
                pagination={false}
                columns={columns}
                dataSource={data.issue_tags}
                rowKey={(record) => record.id}
              ></Table>
            </div>
          </div>
        );
      } else if(data && data.issue_tags && data.issue_tags.length === 0) {
        return <NoneData _html="暂时还没有相关数据!" />
      }
    };

    return (
      <WhiteBack>
        <div
          className="flex-a-center baseForm bbr"
          style={{ "justify-content": "space-between" }}
        >
          <span className="font-18 text-black">项目标签</span>
          {data && data.user_admin_or_member ? (
            <Button type="primary" ghost onClick={this.newshow}>
              <Icon type="plus"></Icon>
              创建标签
            </Button>
          ) : (
            ""
          )}
        </div>
        <div>
          <div style={{ display: this.state.display }} className="padding15">
            <Form>
              <div className="new-tag-div">
                <Form.Item className="inptwidth">
                  {getFieldDecorator("name", {
                    rules: [
                      {
                        required: true,
                        message: "请填写标签名字",
                      },
                    ],
                  })(<Input placeholder="标签名字" maxLength="20" />)}
                </Form.Item>

                <Form.Item className="inputcount">
                  {getFieldDecorator("description", {
                    rules: [
                      {
                        required: true,
                        message: "描述不能为空",
                      },
                    ],
                  })(<Input placeholder="描述, 30字以内" maxLength="30" />)}
                </Form.Item>

                <div>
                  <div style={styles.swatch} onClick={this.handleClick}>
                    <div style={styles.color}>
                      <p style={{ paddingLeft: 25 }}>{this.state.textcolor}</p>
                    </div>
                  </div>
                  {this.state.displayColorPicker ? (
                    <div style={styles.popover}>
                      <div style={styles.cover} onClick={this.handleClose} />
                      <SketchPicker
                        color={this.state.color}
                        onChange={this.handleChange}
                      />
                    </div>
                  ) : null}
                </div>
                <div className="fr" style={{ marginTop: 5 }}>
                  <Button
                    type="primary"
                    onClick={this.createtagpost}
                    className="fr"
                  >
                    创建标签
                  </Button>
                  {/* <a onClick={this.createtagpost} className="topWrapper_btn fr" >创建标签</a> */}
                  <a onClick={this.newclose} className="a_btn cancel_btn fr">
                    取消
                  </a>
                </div>
              </div>
            </Form>
          </div>
          <div className="padding20-30">
            <Spin spinning={isSpin}><div style={{minHeight:"350px"}}>{renderList()}</div></Spin>
            {Paginations}
          </div>
        </div>
        <Modal
          title="编辑标签"
          onCancel={this.handleCancel}
          visible={this.state.isShow}
          onOk={this.handleok}
          mask={true}
          width="600px"
          closable={false}
        >
          <div className="dialogdiv">
            <Input
              placeholder="标签名字"
              maxLength="20"
              className="inptwidth"
              value={this.state.name}
              onChange={this.changmodelname}
            />
            <Input
              placeholder="描述, 30字以内"
              maxLength="30"
              className="inputcount"
              value={this.state.description}
              onChange={this.changdescription}
            />
            <div>
              <div style={styles.swatch} onClick={this.handleClick}>
                <div style={styles.modalcolor}>
                  <p style={{ paddingLeft: 25, width: 100 }}>
                    {this.state.newcolor}
                  </p>
                </div>
              </div>
              {this.state.displayColorPicker ? (
                <div style={styles.popover}>
                  <div style={styles.cover} onClick={this.handleClose} />
                  <SketchPicker
                    color={this.state.color}
                    onChange={this.handleChange}
                  />
                </div>
              ) : null}
            </div>
          </div>
        </Modal>
      </WhiteBack>
    );
  }
}
const WrappedTags = Form.create({ name: "tageFrom" })(NewTags);
export default WrappedTags;
