import React from "react";
import $ from "jquery/src/ajax";
import "react-quill/dist/quill.bubble.css";
import {companyList, getCompanyName, getCompanyValueArray} from '../../common/configure';
import {
  Form,
  Icon,
  Button,
  Input,
  Select,
  Table,
  message,
  DatePicker,
  Modal,
  Upload,
  Popconfirm,
  Cascader,
  InputNumber,
  Radio,
  TimePicker,
  Tabs,
  Tag,
  Checkbox, Tooltip
} from "antd";
import { areaSelect, getProvince } from "@/NewDicProvinceList"; //省市区
import {
  getGameState,
  splitUrl,
  getprovince,
  getStatuslist,
  getLvl,
  beforeUploadFile,
  getPicPath
} from "@/tools.js";
import SpinContainer from "../../SpinContainer";
const { Option } = Select;


const PicturesWall = React.createClass({
  getInitialState() {
    return {
      previewVisible: false,
      previewImage: "",
      fileList: [],
      locations: [],
      locationSearch:'',
      indeterminate:false,
    };
  },
  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.state.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/purchase/uploadPicture"}
          // url: '//172.16.0.253:8080' + '/api/admin/banners/addBanners',
          action={globalConfig.context + "/api/admin/banners/uploadFile"}
          data={{ sign: "purchase_picture" }}
          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={this.handleCancel}
        >
          <img alt="" style={{ width: "100%" }} src={previewImage} />
        </Modal>
      </div>
    );
  }
});
//主体
const AdvertisementList = Form.create()(
  React.createClass({
    loadData(pageNo) {
      this.state.data = [];
      this.setState({
        loading: true,
        page: pageNo
      });
      $.ajax({
        method: "get",
        dataType: "json",
        // url: globalConfig.context + '/api/admin/listCases',
        url: globalConfig.context + "/api/admin/banners/listBanners",
        data: {
          pageNo: pageNo || this.state.pagination.current || 1,
          pageSize: this.state.pagination.pageSize,
          position: this.state.positionSearch,
          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,
        imgeditvisible: false,
        activeKey: "1",
        purchaseImg: [],
        maximg: "",
        timesArr: [],
        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: "position",
            key: "position",
            render: text => {
              if (text == 0) {
                return <span>首页</span>;
              }else if(text == 1) {
                return <span>产品中心</span>;
              }else if(text == 2) {
                return <span>战略合作</span>;
              }else if(text == 3) {
                return <span>服务客户</span>;
              }else if(text == 4) {
                return <span>新闻动态</span>;
              }else if(text == 5) {
                return <span>关于科德</span>;
              }else if(text == 6) {
                return <span>联系我们</span>;
              }else {
                return "未知"
              }
            }
          },
          {
            title: "广告缩略图",
            dataIndex: "bannerUrl",
            key: "bannerUrl",
            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 => {
                      this.stopPropagation(e);
                      this.maximg(path);
                    }}
                  >
                    查看大图
                  </Button>
                </div>
              );
            }
          },
          {
            title: "公司",
            dataIndex: "locations",
            key: "locations",
            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: "display",
            key: "display",
            render: s => {
              return s ? (
                <Tag color="#87d068">显示</Tag>
              ) : (
                <Tag color="#f50">未显示</Tag>
              );
            }
          },
          {
            title: "排序",
            dataIndex: "sort",
            key: "sort"
          },
          {
            title: "操作",
            dataIndex: "c",
            render: (text, record, index) => {
              return (
                <div>
                  {
                    <Button
                      type="primary"
                      onClick={event => {
                        this.stopPropagation(event);
                        this.tableRowClick(record);
                      }}
                    >
                      编辑
                    </Button>
                  }
                  {
                    <Popconfirm
                      okText="确定"
                      cancelText="取消"
                      title="您确定删除？删除后，广告将不再显示"
                      onConfirm={() => {
                        this.delete(record.id);
                      }}
                    >
                      <Button
                        type="danger"
                        style={{ marginLeft: "10px" }}
                        onClick={event => {
                          this.stopPropagation(event);
                        }}
                      >
                        删除
                      </Button>
                    </Popconfirm>
                  }
                  {!record.display ? (
                    <Button
                      type="primary"
                      style={{ marginLeft: "10px" }}
                      onClick={event => {
                        this.stopPropagation(event);
                        this.edit(record, "1");
                      }}
                    >
                      显示
                    </Button>
                  ) : (
                    <Button
                      type="primary"
                      style={{ marginLeft: "10px" }}
                      onClick={event => {
                        this.stopPropagation(event);
                        this.edit(record, "0");
                      }}
                    >
                      隐藏
                    </Button>
                  )}
                </div>
              );
            }
          }
        ],
        //数据列表
        dataSource: [
        ]
      };
    },

    componentWillMount() {
      this.loadData();
    },
    detailes(record) {
      this.setState({
        loading: true
      });
      $.ajax({
        method: "get",
        dataType: "json",
        crossDomain: false,
        url: globalConfig.context + "/api/admin/banners/selectBanners",
        data: {
          id: record.id
        },
        success: function(data) {
          let thisdata = data.data;
          this.setState({
            id: thisdata.id,
            title: thisdata.title,
            bannerUrl: thisdata.bannerUrl
              ? splitUrl(thisdata.bannerUrl, ",", globalConfig.avatarUploadHost)
              : [],
            sortNumber: thisdata.sort,
            display: thisdata.display,
            position: thisdata.position,
            locations: thisdata.locations,
            checked:thisdata.locations.length === companyList.length,
            indeterminate: thisdata.locations.length < companyList.length,
          });
        }.bind(this)
      }).always(
        function() {
          this.setState({
            loading: false
          });
        }.bind(this)
      );
    },
    //点击大图
    maximg(url) {
      this.setState({
        imgeditvisible: true,
        maximg: url
      });
    },
    //删除按钮
    delete(id) {
      $.ajax({
        method: "post",
        dataType: "json",
        crossDomain: false,
        url: globalConfig.context + "/api/admin/banners/deleteBanners",
        data: {
          id
        },
        success: function(data) {
          this.loadData();
        }.bind(this)
      }).always(
        function() {
          this.setState({
            loading: false
          });
        }.bind(this)
      );
    },
    //阻止默认冒泡
    stopPropagation(e) {
      e.stopPropagation();
      e.nativeEvent.stopImmediatePropagation();
    },
    imghandleCancel() {
      this.setState({
        imgeditvisible: false
      });
    },
    //项目列表整行点击
    tableRowClick(record, index) {
      this.state.RowData = record;
      this.setState({
        editvisible: true
      });
      this.detailes(record);
    },
    edithandleCancel(e) {
      this.setState(
        {
          editvisible: false
        },
        () => {
          this.addReset();
        }
      );
      this.loadData();
    },

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

    add() {
      this.setState({
        editvisible: true,
        flag: false
      });
      this.addReset();
    },
    cancelAdd() {
      this.setState(
        {
          editvisible: false
        },
        () => {
          this.setState({
            flag: true
          });
          this.addReset();
        }
      );
      this.loadData();
    },
    edit(record, display) {
      if (!display) {
        if (!this.state.bannerUrl || !this.state.bannerUrl.length) {
          message.warning("请上传图片!");
          return;
        }
        if (!this.state.title) {
          message.warning("请填写广告标题");
          return;
        }
        if(this.state.locations.length === 0){
          message.warning("请选择公司");
          return;
        }
      }
      $.ajax({
        method: "post",
        dataType: "json",
        url: globalConfig.context + "/api/admin/banners/updateBanners",
        data: {
          id: record ? record.id : this.state.id,
          sort: this.state.sortNumber,
          display: display || this.state.display,
          locations: this.state.locations.join(','),
          position: this.state.position,
          bannerUrl: this.state.bannerUrl
            ? this.state.bannerUrl[0].response.data
            : undefined,
          title: this.state.title
        },
        success: function(data) {
          let theArr = [];
          if (data.error.length || data.data.list == "") {
            if (data.error && data.error.length) {
              message.warning(data.error[0].message);
            }
          } else {
            this.cancelAdd();
          }
        }.bind(this)
      }).always(
        function() {
          this.setState({
            loading: false
          });
        }.bind(this)
      );
    },
    addNew() {
      if (!this.state.bannerUrl || !this.state.bannerUrl.length) {
        message.warning("请上传图片!");
        return;
      }
      if (!this.state.title) {
        message.warning("请填写广告标题");
        return;
      }
      if(this.state.locations.length === 0){
        message.warning("请选择公司");
        return;
      }
      $.ajax({
        method: "post",
        dataType: "json",
        url: globalConfig.context + "/api/admin/banners/addBanners",
        data: {
          sort: this.state.sortNumber,
          display: this.state.display,
          locations: this.state.locations.join(','),
          position: this.state.position,
          bannerUrl: this.state.bannerUrl
            ? this.state.bannerUrl[0].response.data
            : undefined,
          title: this.state.title
        },
        success: function(data) {
          let theArr = [];
          if (data.error.length || data.data.list == "") {
            if (data.error && data.error.length) {
              message.warning(data.error[0].message);
            }
          } else {
            message.warning('添加成功');
            this.loadData();
            this.cancelAdd();
          }
        }.bind(this)
      }).always(
        function() {
          this.setState({
            loading: false
          });
        }.bind(this)
      );
    },

    //新增框的清零
    addReset() {
      this.setState({
        bannerUrl: undefined,
        title: undefined,
        sortNumber: undefined,
        display: 1,
        position: "0",
        locations: [],
        indeterminate: false,
        checked:false,
      });
    },
    //搜索部分的清零
    reset() {
      this.setState({
        locationSearch: undefined,
        positionSearch: undefined,
      },()=>{
        this.loadData();
      })
    },
    imgOk() {
      this.setState({
        imgeditvisible: false
      });
    },
    getOrgCodeUrl(e) {
      this.setState({ bannerUrl: e });
    },

    render() {
      const FormItem = Form.Item;
      const rowSelection = {
        selectedRowKeys: this.state.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          this.setState({
            selectedRows: selectedRows.slice(-1),
            selectedRowKeys: selectedRowKeys.slice(-1)
          });
        }
      };
      const { TextArea } = Input; //文本域
      const { TabPane } = Tabs; //标签页
      const { MonthPicker, RangePicker, WeekPicker } = DatePicker; //日期输入框
      const dateFormat = "YYYY/MM/DD"; //日期格式
      const theData = this.state.data || {};
      return (
        <div className="user-content">
          <div className="content-title">
            <span>广告列表</span>
            <div className="user-search">
              <Select
                placeholder="请选择广告位置"
                style={{ width: 150 }}
                value={
                  this.state.positionSearch
                    ? this.state.positionSearch + ""
                    : []
                }
                onChange={e => {
                  this.setState({
                    positionSearch: e
                  });
                }}
              >
                <Option value="0">首页</Option>
                <Option value="1">产品中心</Option>
                <Option value="2">战略合作</Option>
                <Option value="3">服务客户</Option>
                <Option value="4">新闻动态</Option>
                <Option value="5">关于科德</Option>
                <Option value="6">联系我们</Option>
              </Select>
              <Select
                  placeholder="请选择公司"
                  style={{ width: 150 }}
                  value={this.state.locationSearch}
                  onChange={e => {
                    this.setState({
                      locationSearch: e
                    });
                  }}
              >
                {
                  companyList.map((v)=>(
                      <Option key={v.value} value={v.value}>{v.label}</Option>
                  ))
                }
              </Select>
              <Button
                type="primary"
                onClick={this.search}
                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}
                  onRowClick={this.tableRowClick}
                  pagination={this.state.pagination}
                  bordered
                  size="small"
                />
              </SpinContainer>
            </div>
          </div>
          <div className="patent-desc">
            <Modal
              className="customeDetails"
              title={this.state.flag ? "广告详情" : "新增广告"}
              visible={this.state.editvisible}
              onOk={this.edithandleCancel}
              width={"690px"}
              onCancel={
                this.state.flag ? this.edithandleCancel : this.cancelAdd
              }
              footer=""
            >
              <Form
                layout="horizontal"
                onSubmit={this.edithandleSubmit}
                id="demand-form"
              >
                <SpinContainer spinning={this.state.loading}>
                  <div className="clearfix">
                    <FormItem
                      className="half-item"
                      labelCol={{ span: 8 }}
                      wrapperCol={{ span: 12 }}
                      label="广告位置"
                    >
                      <Select
                        placeholder="请选择广告位置"
                        value={this.state.position + ""}
                        onChange={e => {
                          this.setState({
                            position: e
                          });
                        }}
                      >
                        <Option value="0">首页</Option>
                        <Option value="1">产品中心</Option>
                        <Option value="2">战略合作</Option>
                        <Option value="3">服务客户</Option>
                        <Option value="4">新闻动态</Option>
                        <Option value="5">关于科德</Option>
                        <Option value="6">联系我们</Option>
                      </Select>
                    </FormItem>
                    <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>
                    </div>
                    <div className="clearfix">
                      <FormItem
                        className="half-item"
                        labelCol={{ span: 8 }}
                        wrapperCol={{ span: 12 }}
                        label="排序"
                      >
                        <Input
                          placeholder="请输入排序"
                          value={this.state.sortNumber}
                          onChange={e => {
                            this.setState({ sortNumber: e.target.value });
                          }}
                          style={{ width: "240px" }}
                        />
                      </FormItem>
                    </div>

                    <div className="clearfix">
                      <FormItem
                          className="half-item"
                          labelCol={{ span: 8 }}
                          wrapperCol={{ span: 12 }}
                          label="是否显示"
                      >
                        <Radio.Group
                            onChange={e => {
                              this.setState({
                                display: e.target.value
                              });
                            }}
                            value={this.state.display}
                        >
                          <Radio value={1}>是</Radio>
                          <Radio value={0}>否</Radio>
                        </Radio.Group>
                      </FormItem>
                    </div>
                  </div>
                  <div className="clearfix">
                    <FormItem
                        className="half-item"
                        labelCol={{ span: 8 }}
                        wrapperCol={{ span: 14 }}
                        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 }}
                      label="广告大图"
                    >
                      <PicturesWall
                        fileList={this.getOrgCodeUrl}
                        pictureUrl={this.state.bannerUrl}
                      />
                      <p>图片建议：要清晰。</p>
                    </FormItem>
                  </div>
                  <div className="clearfix">
                    <Button
                      type="primary"
                      size="large"
                      onClick={() => {
                        this.state.flag ? this.edit() : this.addNew();
                      }}
                      style={{
                        display: "block",
                        margin: "auto"
                      }}
                    >
                      保存
                    </Button>
                  </div>
                </SpinContainer>
              </Form>
            </Modal>
          </div>
          <Modal
            visible={this.state.imgeditvisible}
            onCancel={this.imghandleCancel}
            onOk={this.imgOk}
          >
            <img style={{ width: "100%" }} src={this.state.maximg} />
          </Modal>
        </div>
      );
    }
  })
);

export default AdvertisementList;
