import React from 'react';
import $ from 'jquery/src/ajax';
import {
  Form, Button, Input, Select, InputNumber, Spin, Table,
  message, DatePicker, Modal, Tabs
} from 'antd';
import moment from 'moment';
import { ShowModal, } from '../../../tools.js';
import { ChooseList } from "../../order/orderNew/chooseList";
import "./index.less";

const { TabPane } = Tabs
const FormItem = Form.Item;
const Standard = Form.create()(React.createClass({

  getInitialState() {
    return {
      searchValues: {},
      loading: false,
      changeList: undefined, // 更改后的表格显示数据
      dataSource: [],
      pagination: {
        defaultCurrent: 1,
        defaultPageSize: 10,
        showQuickJumper: true,
        pageSize: 20,
        onChange: function (page) {
          this.loadData(page);
        }.bind(this),
        showTotal: function (total) {
          return '共' + total + '条数据';
        }
      },
      columns: [
        {
          title: '链接',
          dataIndex: 'url',
          key: 'url',
          width: 360,
          render: text =>
            <a href={text} target="_blank">{text}</a>
            // <div onClick={e => {
            //   window.open(text)
            // }}>
            //   {text}
            // </div>
        },
        {
          title: '标准平台',
          dataIndex: 'name',
          key: 'name',
        },
        {
          title: '排序',
          dataIndex: 'sort',
          key: 'sort',
        },
        {
          title: '状态',
          dataIndex: 'status',
          key: 'status',
          render: text => <span style={{ color: ["red", "green"][text] }}>{["关闭", "开启"][text]}</span>
        },
        {
          title: '更新时间',
          dataIndex: 'updateTime',
          key: 'updateTime',
        },
      ],
      visible: "",
      data: {},
    };
  },

  componentWillMount() {
    this.loadData();
  },
  // 列表接口
  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/standardPlatformLink/list",
      data: datas,
      success: function (data) {
        ShowModal(this);
        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,
            });
          } 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)
    );
  },
  // 搜索
  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
    });
  },

  addClick() {
    this.setState({
      visible: "add"
    })
  },

  tableRowClick(e) {
    if (!adminData.isSuperAdmin) {
      return
    }
    this.setState({
      visible: "edit",
    })
    this.getDetails(e.id)
  },
  // 数据详情
  getDetails(id) {
    this.setState({
      loading: true
    });
    $.ajax({
      method: "get",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + "/api/admin/standardPlatformLink/get",
      data: {
        id,
      },
      success: function (data) {
        let thedata = data.data || {};
        if (!thedata) {
          if (data.error && data.error.length) {
            message.warning(data.error[0].message);
          };
        }
        this.setState({
          data: thedata,
        })
      }.bind(this),
    }).always(function () {
      this.setState({
        loading: false
      });
    }.bind(this));
  },

  handleCancel() {
    this.setState({
      visible: "",
      data: {},
    })
  },
  // 提交保存
  handleSubmit() {
    const { data } = this.state
    if (!data.name) {
      message.warning('标准平台名称不能为空！');
      return;
    }
    if (!data.url) {
      message.warning('链接不能为空！');
      return;
    }
    if (!data.sort && data.sort != 0) {
      message.warning('排序不能为空！');
      return;
    }
    if (!data.status && data.status != 0) {
      message.warning('请选择状态！');
      return;
    }
    if (data.id) {
      delete data.createTime;
      delete data.updateTime;
      delete data.aid;
    }
    $.ajax({
      method: "POST",
      dataType: "json",
      crossDomain: false,
      url:
        data.id
          ? globalConfig.context + '/api/admin/standardPlatformLink/update'
          : globalConfig.context + '/api/admin/standardPlatformLink/add',
      data,
    }).done(function (data) {
      this.setState({
        loading: false
      });
      if (!data.error.length) {
        message.success('保存成功！');
        this.handleCancel();
        this.loadData(this.state.pageNo);
      } else {
        message.warning(data.error[0].message);
      }
    }.bind(this));
  },

  render() {
    const { RangePicker } = DatePicker;
    const { searchValues, data } = this.state
    const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
    };
    return (
      <div className="user-content">
        <div className="content-title">
          <Tabs defaultActiveKey="1" className="test">
            <TabPane tab="搜索" key="1">
              <div className="user-search" style={{ marginLeft: 10 }}>
                <Input
                  placeholder="请输入标准平台"
                  value={searchValues["name"]
                    ? searchValues["name"]
                    : ""}
                  onChange={(e) => {
                    searchValues["name"] = e.target.value;
                    this.setState({
                      searchValues: searchValues,
                    });
                  }}
                />
                <Select
                  placeholder="状态"
                  style={{ width: 140 }}
                  value={searchValues["status"]}
                  onChange={(e) => {
                    searchValues["status"] = e;
                    this.setState({
                      searchValues: searchValues,
                    });
                  }}
                >
                  <Select.Option value={null}>全部</Select.Option>
                  <Select.Option value={0}>关闭</Select.Option>
                  <Select.Option value={1}>开启</Select.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 style={{ marginLeft: 10 }}>
                <ChooseList
                  columns={this.state.columns}
                  changeFn={this.changeList}
                  changeList={this.state.changeList}
                  top={55}
                  margin={11}
                />
              </div>
            </TabPane>
            {adminData.isSuperAdmin ?
              <TabPane tab="新增" key="3">
                <Button
                  type="primary"
                  className="addButton"
                  style={{ float: "left", marginBottom: 10, marginTop: 12 }}
                  onClick={this.addClick}
                >
                  新增
                </Button>
              </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>
        </div>
        {
          this.state.visible != "" &&
          <Modal
            title={!!data.id ? "编辑标准平台链接" : "新增标准平台链接"}
            visible={this.state.visible != ""}
            width="600px"
            onCancel={this.handleCancel}
            maskClosable={false}
            footer=""
            className="admin-desc-content"
          >
            <Form
              layout="horizontal"
              // onSubmit={this.handleSubmit}
              id="demand-form"
            >
              <Spin spinning={this.state.loading}>
                <div className="clearfix">
                  <FormItem
                    className="half-middle"
                    {...formItemLayout}
                    label="标准平台链接"
                  >
                    <Input
                      placeholder="请输入标准平台链接"
                      value={data["url"]
                        ? data["url"]
                        : ""}
                      style={{ width: "230px" }}
                      onChange={(e) => {
                        data["url"] = e.target.value;
                        this.setState({
                          data: data
                        });
                      }}
                    />
                    <span className="mandatory">*</span>
                  </FormItem>
                  <FormItem
                    className="half-middle"
                    {...formItemLayout}
                    label="标准平台名称"
                  >
                    <Input
                      placeholder="请输入标准平台名称"
                      value={data["name"]
                        ? data["name"]
                        : ""}
                      style={{ width: "230px" }}
                      onChange={(e) => {
                        data["name"] = e.target.value;
                        this.setState({
                          data: data
                        });
                      }}
                    />
                    <span className="mandatory">*</span>
                  </FormItem>
                  <FormItem
                    className="half-middle"
                    {...formItemLayout}
                    label="排序"
                  >
                    <InputNumber
                      min={0}
                      max={999999}
                      step={1}
                      value={data["sort"]
                        ? data["sort"]
                        : ""}
                      style={{ width: "130px" }}
                      onChange={(e) => {
                        data["sort"] = e;
                        this.setState({
                          data: data
                        });
                      }}
                    />
                    <span className="mandatory">数字越大排序越前</span>
                  </FormItem>
                  <FormItem
                    className="half-middle"
                    {...formItemLayout}
                    label="状态"
                  >
                    <Select
                      placeholder=""
                      style={{ width: "80px" }}
                      value={data.status}
                      onChange={(e) => {
                        data["status"] = e;
                        this.setState({
                          data: data,
                        });
                      }}
                    >
                      {[
                        { key: "关闭", value: 0 },
                        { key: "开启", value: 1 },
                      ].map(function (item) {
                        return (
                          <Select.Option key={item.value} value={item.value}>
                            {item.key}
                          </Select.Option>
                        );
                      })}
                    </Select>
                    <span className="mandatory">*</span>
                  </FormItem>

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

export default Standard;
