import React from "react";
import $ from "jquery/src/ajax";
import "react-quill/dist/quill.bubble.css";
import moment from "moment";
import "../authentication/techDemand.less";
import {
  Form,
  Icon,
  Button,
  Input,
  Select,
  Table,
  message,
  DatePicker,
  Modal,
  Upload,
  Popconfirm,
  Tabs,
  Tag, Checkbox, Tooltip
} from "antd";
import {
  splitUrl,
  beforeUploadFile,
  getPicPath
} from "@/tools.js";
import Editors from "@/richTextEditors";
import SpinContainer from "../../SpinContainer";
import {companyList, getCompanyName, getCompanyValueArray} from "../../common/configure"; //富文本编辑器

// 上传文件
const PicturesWall = React.createClass({
  getInitialState() {
    return {
      previewVisible: false,
      previewImage: "",
      fileList: [],
    };
  },
  getDefaultProps() {
    return {
      changeClick: this.modifyChange
    };
  },
  handleCancel() {
    this.setState({ previewVisible: false });
  },
  handlePreview(file) {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true
    });
  },
  handleChange(info) {
    let fileList = info.fileList;
    this.setState({ fileList });
    this.props.fileList(fileList);
  },
  componentWillReceiveProps(nextProps) {
    this.setState({
      fileList: nextProps.pictureUrl
    })
  },
  render() {
    const { previewVisible, previewImage, fileList } = this.state;
    // 点击上传
    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">点击上传</div>
      </div>
    );
    return (
      //上传组件
      <div style={{ display: "inline-block" }}>
        <Upload
          beforeUpload={beforeUploadFile}
          // action={globalConfig.context + "/api/admin/militaryEnterprises/uploadPicture"}
          action={globalConfig.context + "/api/admin/news/uploadFile"}
          data={{ sign: "enterprises_pucture" }}
          listType="picture-card"
          fileList={fileList}
          onPreview={this.handlePreview}
          onChange={this.handleChange}
        >
          {fileList && fileList.length >= 1 ? null : uploadButton}
        </Upload>
        <Modal
          maskClosable={false}
          visible={previewVisible}
          footer={null}
          onCancel={e => {
            this.setState({ previewVisible: false });
          }}
        >
          <img alt="" style={{ width: "100%" }} src={previewImage} />
        </Modal>
      </div>
    );
  }
});
//主体
const FirmList = Form.create()(
  React.createClass({
    // 初始化数据
    loadData(pageNo) {
      this.state.data = [];
      this.setState({
        loading: true,
        page: pageNo
      });
      //发送请求
      $.ajax({
        method: "get",
        dataType: "json",
        crossDomain: false,
        url: globalConfig.context + "/api/admin/news/listNews",
        data: {
          pageNo: pageNo || this.state.pagination.current || 1,
          pageSize: this.state.pagination.pageSize,
          title: this.state.titleSearch,
          location: this.state.locationSearch,
        },
        success: function(data) {
          let theArr = [];
          if (!data.data || !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];
              thisdata.key = i + 1
              theArr.push(thisdata);
            }
            this.state.pagination.current = data.data.pageNo;
            this.state.pagination.total = data.data.totalCount;
          }
          this.setState({
            dataSource: theArr,
            pagination: this.state.pagination
          });
        }.bind(this)
      }).always(
        function() {
          this.setState({
            loading: false
          });
        }.bind(this)
      );
    },
    //声明状态
    getInitialState() {
      return {
        loading: false,
        flag: true,
        editorState: null,
        locations: [],
        indeterminate: false,
        activeKey: "1",
        timesArr: [],
        ProvinceCity: [],
        ProvinceCityC: [],
        totalData: {
          mark: false
        },
        imgWidth: "width: 200px",
        logoUrl: [],
        pagination: {
          defaultCurrent: 1,
          defaultPageSize: 10,
          showQuickJumper: true,
          pageSize: 10,
          onChange: function(page) {
            this.loadData(page);
            this.setState({
              selectedRowKeys: []
            });
          }.bind(this),
          showTotal: function(total) {
            return "共" + total + "条数据";
          }
        },
        //数据类型
        columns: [
          {
            title: "序号",
            dataIndex: "key",
            key: "key"
          },
          {
            title: "新闻分类",
            dataIndex: "type",
            key: "type",
            render: text => {
              if (text == 0) {
                return "公司新闻";
              } else if (text == 1) {
                return "行业新闻";
              }
            }
          },
          {
            title: "新闻标题",
            dataIndex: "title",
            key: "title",
            render: text => {
              return text.length >= 8 ? text.substring(0, 8) + "..." : text;
            }
          },
          {
            title: "排序",
            dataIndex: "sort",
            key: "sort"
          },
          {
            title: "是否首页",
            dataIndex: "status",
            key: "status",
            render: s => {
              return s ? (
                <Tag color="#87d068">是</Tag>
              ) : (
                <Tag color="#f50">否</Tag>
              );
            }
          },
          {
            title: "新闻缩率图",
            dataIndex: "pictureUrl",
            key: "pictureUrl",
            render: url => {
              let path = getPicPath(globalConfig.avatarUploadHost, url);
              return (
                <div style={{ textAlign: "center" }}>
                  <img src={path} style={{ width: "100px", height: 50 }} />
                  <Button
                    className="buttonimg"
                    style={{ marginLeft: 10 }}
                    onClick={e => {
                      e.stopPropagation();
                      this.maximg(path);
                    }}
                  >
                    查看大图
                  </Button>
                </div>
              );
            }
          },
          {
            title: "公司",
            dataIndex: "locations",
            key: "locations",
            width:150,
            render: r => {
              let text = '';
              r && r.map((v,i)=>(
                  text += (i === 0 ? '':',')+getCompanyName(v)
              ))
              return(
                  <Tooltip placement="top" title={text}>
                    {
                      r && r.map((v,i)=>(
                          i <= 2 ? (i === 0 ? '':',')+getCompanyName(v) : null
                      ))
                    }
                    {
                      r.length > 3 ? '.....' : null
                    }
                  </Tooltip>
              )
            }
          },
          {
            title: "发布状态",
            dataIndex: "releaseStatus",
            key: "releaseStatus",
            render: text => {
              return text ? "是" : "否";
            }
          },
          //   {
          //     title: "置顶",
          //     dataIndex: "topNumber",
          //     key: "topNumber",
          //     render: text => {
          //       return text ? "否" : "是";
          //     }
          //   },
          {
            title: "操作",
            dataIndex: "operate",
            key: "operate",
            render: (text, record, index) => {
              return (
                <div>
                  <Button
                    type="primary"
                    style={{ marginLeft: "10px" }}
                    onClick={() => {
                      this.setState({
                        flag: true
                      });
                      this.edit(record);
                    }}
                  >
                    编辑
                  </Button>
                  <Popconfirm
                    title="您确定删除该新闻吗？"
                    onConfirm={() => this.confirm(record.id)}
                    onCancel={this.cancel}
                    okText="是"
                    cancelText="否"
                  >
                    <Button
                      type="danger"
                      style={{ marginLeft: "10px" }}
                      onClick={e => {
                        e.stopPropagation();
                      }}
                    >
                      删除
                    </Button>
                  </Popconfirm>
                  <Button
                    type="primary"
                    style={{ marginLeft: "10px" }}
                    onClick={e => {
                      e.stopPropagation();
                      if (record.status) {
                        this.toTop(record, 0);
                      } else {
                        this.toTop(record, 1);
                      }
                    }}
                  >
                    {record.status ? "从首页撤下" : "推荐至首页"}
                  </Button>
                </div>
              );
            }
          },
          {
            title: "发布时间",
            dataIndex: "releaseTimeConvert",
            key: "releaseTimeConvert"
          }
        ],
        //数据列表
        dataSource: []
      };
    },
    // 新增新闻按钮
    add() {
      this.setState({
        editvisible: true,
        flag: false
      });
    },
    // 推荐置顶
    toTop(record, num) {
      $.ajax({
        method: "post",
        dataType: "json",
        crossDomain: false,
        url: globalConfig.context + "/api/admin/news/updateNews",
        data: {
          id: record.id,
          status: num
        },
        success: function(data) {
          let theArr = [];
          if (data.error && data.error.length) {
            message.warning(data.error[0].message);
          } else {
            this.loadData();
          }
        }.bind(this)
      }).always(
        function() {
          this.setState({
            loading: false
          });
        }.bind(this)
      );
    },
    //编辑按钮操作
    tableRowClick(record) {
      this.setState({
        editvisible: true,
        flag: true,
      },()=>{
        this.edit(record);
      });
    },
    edit(record, index) {
      this.setState({
        editvisible: true,
        loading: true
      });
      $.ajax({
        method: "get",
        dataType: "json",
        crossDomain: false,
        url: globalConfig.context + "/api/admin/news/selectNews",
        data: {
          id: record.id
        },
        success: function(data) {
          let theArr = [];
          if (data.error && data.error.length) {
            message.warning(data.error[0].message);
          } else {
            let thisdata = data.data;
            this.setState({
              id: thisdata.id,
              title: thisdata.title,
              publisher: thisdata.publisher,
              type: thisdata.type,
              pictureUrl: thisdata.pictureUrl
                ? splitUrl(
                    thisdata.pictureUrl,
                    ",",
                    globalConfig.avatarUploadHost
                  )
                : [],
              sort: thisdata.sort,
              checked:thisdata.locations.length === companyList.length,
              indeterminate: thisdata.locations.length < companyList.length,
              locations: thisdata.locations,
              editorcontext: thisdata.content,
              releaseStatus: thisdata.releaseStatus,
              time: thisdata.releaseTimeConvert
                ? thisdata.releaseTimeConvert
                : thisdata.createTimeConvert
            });
            window.setTimeout(() => {
              console.log(this.state);
            }, 100);
          }
        }.bind(this)
      }).always(
        function() {
          this.setState({
            loading: false
          });
        }.bind(this)
      );
    },
    getOrgCodeUrl(e) {
      this.setState({ pictureUrl: e });
    },
    // 新增新闻
    addNew(flag) {
      if(!this.state.locations || this.state.locations.length === 0 ){
        message.warning('请选择公司');
        return ;
      }
      if(!this.state.pictureUrl || this.state.pictureUrl.length === 0){
        message.warning('请选择新闻大图');
        return ;
      }
      if (this.state.flag) {
        $.ajax({
          method: "post",
          dataType: "json",
          crossDomain: false,
          url: globalConfig.context + "/api/admin/news/updateNews",
          data: {
            id: this.state.id,
            title: this.state.title,
            publisher: this.state.publisher,
            type: this.state.type,
            pictureUrl: this.state.pictureUrl
              ? this.state.pictureUrl[0].response.data
              : undefined,
            sort: this.state.sort,
            locations: this.state.locations.join(','),
            content: this.state.editorcontext,
            status: this.state.status,
            releaseTimes: this.state.time,
            releaseStatus: flag
          },
          success: function(data) {
            let theArr = [];
            if (data.error && data.error.length) {
              message.warning(data.error[0].message);
            } else {
              message.success('操作成功');
              this.loadData();
              this.handleCancelEdit();
            }
          }.bind(this)
        }).always(
          function() {
            this.setState({
              loading: false
            });
          }.bind(this)
        );
      } else {
        $.ajax({
          method: "post",
          dataType: "json",
          crossDomain: false,
          url: globalConfig.context + "/api/admin/news/addNews",
          data: {
            title: this.state.title,
            publisher: this.state.publisher,
            type: this.state.type,
            pictureUrl: this.state.pictureUrl[0].response.data,
            sort: this.state.sort,
            locations: this.state.locations.join(','),
            content: this.state.editorcontext,
            releaseStatus: flag,
            status: 0,
            releaseTimes: this.state.time
          },
          success: function(data) {
            if (data.error && data.error.length) {
              message.warning(data.error[0].message);
            } else {
              message.success('操作成功');
              this.loadData();
              this.handleCancelEdit();
            }
          }.bind(this)
        }).always(
          function() {
            this.setState({
              loading: false
            });
          }.bind(this)
        );
      }
    },
    //表单内容改变时候触发
    change(key, e, f) {
      if (f === undefined) {
        this.state.totalData[key] = e;
        this.setState({
          totalData: this.state.totalData
        });
      } else if (typeof f === "function") {
        this.state.totalData[key] = e;
        this.setState(
          {
            totalData: this.state.totalData
          },
          f
        );
      }
    },
    // 关闭模态框
    handleCancelEdit() {
      this.setState({
        editvisible: false
      });
      this.addReset();
    },
    //点击大图
    maximg(url) {
      this.setState({
        imgeditvisible: true,
        maximg: url
      });
    },
    componentWillMount() {
      this.loadData();
    },
    //确认要删除吗
    confirm(id) {
      $.ajax({
        method: "post",
        dataType: "json",
        crossDomain: false,
        url: globalConfig.context + "/api/admin/news/deleteNews",
        data: {
          id
        },
        success: function(data) {
          let theArr = [];
          if (data.error && data.error.length) {
            message.warning(data.error[0].message);
          } else {
            this.loadData();
          }
        }.bind(this)
      }).always(
        function() {
          this.setState({
            loading: false
          });
        }.bind(this)
      );
    },
    imghandleCancel() {
      this.setState({
        imgeditvisible: false
      });
    },
    //取消删除
    cancel() {
      console.log("我取消删除了");
    },
    async submitContent() {
      // 在编辑器获得焦点时按下ctrl+s会执行此方法
      // 编辑器内容提交到服务端之前，可直接调用editorState.toHTML()来获取HTML格式的内容
      const htmlContent = this.state.editorState.toHTML();
      const result = await saveEditorContent(htmlContent);
    },
    //新增框的清零
    addReset() {
      this.setState({
        pictureUrl: [],
        title: undefined,
        publisher: undefined,
        type: undefined,
        sort: undefined,
        locations: [],
        editorcontext: "",
        time: undefined,
        indeterminate: false,
        checked:false,
      });
    },
    //搜索部分的清零
    reset() {
      this.setState({
        locationSearch: '',
        titleSearch: undefined,
      },()=>{
        this.loadData();
      })
    },

    render() {
      const FormItem = Form.Item;
      const rowSelection = {
        selectedRowKeys: this.state.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          this.setState({
            selectedRows: selectedRows.slice(-1),
            selectedRowKeys: selectedRowKeys.slice(-1)
          });
        }
      };
      let data = this.state.totalData;
      const { TextArea } = Input; //文本域
      const { TabPane } = Tabs; //标签页
      const { MonthPicker, RangePicker, WeekPicker } = DatePicker; //日期输入框
      const { editorState } = this.state;
      return (
        <div className="user-content">
          <div className="content-title">
            <span>新闻列表</span>
            <div className="user-search">
              <Input
                placeholder="请输入新闻标题"
                style={{
                  width: "150px",
                  marginRight: "10px",
                  marginBottom: "10px"
                }}
                value={this.state.titleSearch}
                onChange={e => {
                  this.setState({ titleSearch: e.target.value });
                }}
              />
              <Select
                  placeholder="请选择公司"
                  style={{ width: 150 }}
                  value={this.state.locationSearch}
                  onChange={e => {
                    this.setState({
                      locationSearch: e
                    });
                  }}
              >
                {
                  companyList.map((v)=>(
                      <Select.Option key={v.value} value={v.value}>{v.label}</Select.Option>
                  ))
                }
              </Select>
              <Button
                type="primary"
                onClick={e => {
                  this.loadData();
                }}
                style={{ marginRight: "10px" }}
              >
                搜索
              </Button>
              <Button onClick={this.reset} style={{ marginRight: "10px" }}>
                重置
              </Button>
              <Button
                type="primary"
                onClick={this.add}
                style={{ marginLeft: "100px" }}
              >
                新增新闻
              </Button>
            </div>
            {/* 新闻表单 */}
            <div className="patent-table">
              <SpinContainer spinning={this.state.loading}>
                <Table
                  columns={this.state.columns}
                  dataSource={this.state.dataSource}
                  pagination={this.state.pagination}
                  onRowClick={this.tableRowClick}
                  bordered
                  size="small"
                  ellipsis="true"
                />
              </SpinContainer>
            </div>
          </div>
          {/* 模块框 */}
          <div className="patent-desc">
            <Modal
              className="customeDetails"
              title={this.state.flag ? "新闻详情" : "新增新闻"}
              width="1000px"
              onCancel={this.handleCancelEdit}
              visible={this.state.editvisible}
              footer=""
            >
                <SpinContainer spinning={this.state.loading}>
                  <div className="clearfix">
                    <FormItem
                      className="half-item"
                      labelCol={{ span: 8 }}
                      wrapperCol={{ span: 12 }}
                      label="新闻标题"
                    >
                      <Input
                        placeholder="请输入新闻标题"
                        value={this.state.title}
                        onChange={e => {
                          this.setState({
                            title: e.target.value
                          });
                        }}
                        style={{ width: "240px" }}
                      />
                    </FormItem>
                    <FormItem
                      className="half-item"
                      labelCol={{ span: 8 }}
                      wrapperCol={{ span: 12 }}
                      label="新闻类别"
                    >
                      <Select
                        style={{ width: 120 }}
                        placeholder="请选择新闻类型"
                        value={
                          this.state.type == 1
                            ? "行业新闻"
                            : this.state.type == 0
                            ? "公司新闻"
                            : []
                        }
                        onChange={e => {
                          this.setState({
                            type: e
                          });
                        }}
                      >
                        <Option value="0">公司新闻</Option>
                        <Option value="1">行业新闻</Option>
                      </Select>
                    </FormItem>
                    <FormItem
                      className="half-item"
                      labelCol={{ span: 8 }}
                      wrapperCol={{ span: 12 }}
                      label="新闻发布人"
                    >
                      <Input
                        placeholder="请输入新闻发布人"
                        value={this.state.publisher}
                        onChange={e => {
                          this.setState({
                            publisher: e.target.value
                          });
                        }}
                        style={{ width: "240px" }}
                      />
                    </FormItem>
                    <FormItem
                      className="half-item"
                      labelCol={{ span: 8 }}
                      wrapperCol={{ span: 12 }}
                      label="发布时间"
                    >
                      <DatePicker
                        placeholder="请输入发布时间"
                        format="YYYY-MM-DD HH:mm:ss"
                        showTime
                        value={this.state.time ? moment(this.state.time) : null}
                        onChange={(e, f) => {
                          this.setState({ time: f });
                          console.log(e, f);
                        }}
                        style={{ width: "240px" }}
                      />
                    </FormItem>
                    <FormItem
                      className="half-item"
                      labelCol={{ span: 8 }}
                      wrapperCol={{ span: 12 }}
                      label="排序"
                    >
                      <Input
                        placeholder="请输入排序"
                        value={this.state.sort}
                        onChange={e => {
                          this.setState({
                            sort: e.target.value
                          });
                        }}
                        style={{ width: "240px" }}
                      />
                    </FormItem>
                    <FormItem
                        className="half-item"
                        labelCol={{ span: 8 }}
                        wrapperCol={{ span: 12 }}
                        label="公司"
                    >
                      <Checkbox indeterminate={this.state.indeterminate} checked={this.state.checked} onChange={(e)=>{
                        this.setState({
                          locations: e.target.checked ? getCompanyValueArray():[],
                          indeterminate: false,
                          checked:e.target.checked
                        })
                      }}>全选</Checkbox>
                      <Checkbox.Group
                          options={companyList}
                          value={this.state.locations}
                          onChange={(e) => {
                            this.setState({
                              locations: e,
                              indeterminate: companyList.length > e.length,
                              checked: companyList.length === e.length
                            });
                          }}
                      />
                    </FormItem>
                  </div>
                  <div className="clearfix">
                    <FormItem
                      labelCol={{ span: 4 }}
                      wrapperCol={{ span: 18 }}
                      onCancel={this.handleCancel}
                      label="新闻大图"
                    >
                      <PicturesWall
                        fileList={this.getOrgCodeUrl}
                        pictureUrl={this.state.pictureUrl}
                      />
                      <p>建议尺寸:345X200 图片建议：要清晰。</p>
                    </FormItem>
                  </div>
                  <div className="clearfix">
                    <FormItem
                      labelCol={{ span: 4 }}
                      wrapperCol={{ span: 18 }}
                      label="企业简介"
                    >
                      <Editors
                        textContent={this.state.editorcontext}
                        uploadUrl={"/api/admin/news/uploadFile"}
                        globalConfig={globalConfig.uploadPath}
                        placeholder="业务项目客户基本条件"
                        handleRichText={value => {
                          this.setState({ editorcontext: value });
                        }}
                      />
                    </FormItem>
                  </div>
                  <div className="clearfix">
                    <Button
                      type="primary"
                      size="large"
                      onClick={e => {
                        this.addNew(0);
                      }}
                      style={{
                        float: "right",
                        marginRight: "80px",
                        marginTop: "20px"
                      }}
                    >
                      保存
                    </Button>
                    <Button
                      type="primary"
                      size="large"
                      onClick={e => {
                        this.addNew(1);
                      }}
                      style={{
                        float: "right",
                        marginRight: "20px",
                        marginTop: "20px"
                      }}
                    >
                      保存并发布
                    </Button>
                  </div>
                </SpinContainer>
            </Modal>
            <Modal
              visible={this.state.imgeditvisible}
              onCancel={this.imghandleCancel}
              onOk={this.imgOk}
            >
              <img style={{ width: "100%" }} src={this.state.maximg} />
            </Modal>
          </div>
        </div>
      );
    }
  })
);

export default FirmList;
