import React from "react";
import $ from "jquery/src/ajax";
import "react-quill/dist/quill.bubble.css";
import moment from "moment";
import {
  Form,
  Icon,
  Button,
  Input,
  Select,
  Table,
  message,
  DatePicker,
  Modal,
  Upload,
  Popconfirm,
  Cascader,
  InputNumber,
  Radio,
  Tooltip,
  Tabs,
  Tag, Checkbox
} from "antd";
import { areaSelect, getProvince } from "@/NewDicProvinceList"; //省市区
import {
  getGameState,
  splitUrl,
  getprovince,
  getStatuslist,
  getLvl,
  beforeUploadFile,
  getSecretType,
  getBuyAuditType,
  placeList,
  province,
  provinceStatus,
  getPicPath
} from "@/tools.js";
const { Option } = Select;
import Img01 from "./image/cgg.jpg";
import Img02 from "./image/ttt.jpg";
import Img03 from "./image/xxxd.jpg";
import Img04 from "./image/bbb.jpg";
import SpinContainer from "../../SpinContainer";
import {companyList, getCompanyName, getCompanyValueArray} from "../../common/configure";

//上传图片组件
const PicturesWall = React.createClass({
  getInitialState() {
    return {
      previewVisible: false,
      previewImage: "",
      fileList: this.props.pictureUrl,
      imgflag: this.props.flagimg
    };
  },
  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, flagimg } = this.state;
    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">点击上传</div>
      </div>
    );
    return (
      <div style={{ display: "inline-block" }} className={flagimg}>
        <Upload
          beforeUpload={beforeUploadFile}
          action={globalConfig.context + "/api/admin/customerCase/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 BuyList = 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/customerCase/listCustomerCase",
        data: {
          pageNo: pageNo || this.state.pagination.current || 1,
          pageSize: this.state.pagination.pageSize,
          name: this.state.nameSearch,
          location: this.state.location,
        },
        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,
        timesArr: [],
        totalData: {
          mark: false
        },
        locations:[],
        purchaseImg: [],
        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: "province",
            key: "province",
            render: e => {
              let str = "";
              provinceStatus.forEach(item => {
                if (item.value == e) {
                  str = item.key;
                }
              });
              return str;
            }
          },
          {
            title: "公司名字",
            dataIndex: "name",
            key: "name"
          },
          {
            title: "是否首页",
            dataIndex: "status",
            key: "status",
            render: s => {
              return s ? (
                <Tag color="#87d068">是</Tag>
              ) : (
                <Tag color="#f50">否</Tag>
              );
            }
          },
          {
            title: "LOGO缩率图",
            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: "sort",
            key: "sort"
          },
          {
            title: "操作",
            dataIndex: "ads",
            key: "ads",
            render: (text, record, index) => {
              return (
                <div>
                  {
                    <Button
                      type="primary"
                      onClick={event => {
                        this.stopPropagation(event);
                        this.edit(record);
                      }}
                    >
                      编辑
                    </Button>
                  }
                  {
                    <Popconfirm
                      okText="确定"
                      cancelText="取消"
                      title="您确定删除客户服务信息吗？"
                      onConfirm={() => {
                        this.delete(record.id);
                      }}
                    >
                      <Button
                        type="danger"
                        style={{ marginLeft: "10px" }}
                        onClick={event => {
                          this.stopPropagation(event);
                        }}
                      >
                        删除
                      </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>
              );
            }
          }
        ],
        //数据列表
        dataSource: []
      };
    },
    //点击大图
    maximg(url) {
      this.setState({
        imgeditvisible: true,
        maximg: url
      });
    },
    componentWillMount() {
      this.loadData();
    },
    detailes(record) {
      this.setState({
        loading: true
      });
      $.ajax({
        method: "get",
        dataType: "json",
        crossDomain: false,
        url: globalConfig.context + "/api/admin/purchase/details",
        data: {
          id: record.id
        },
        success: function(data) {
          let theArr = [];
          let thisdata = data.data;
          if (!data.data || !data.data.list) {
            if (data.error && data.error.length) {
              message.warning(data.error[0].message);
            }
          }
          this.setState({
            purchaseImg: thisdata.purchaseImg
              ? splitUrl(
                  thisdata.purchaseImg,
                  ",",
                  globalConfig.avatarUploadHost + "/upload"
                )
              : []
          });
          Object.assign(
            this.state.totalData,
            {
              content: thisdata.content,
              contacts: thisdata.contacts,
              contactsMobile: thisdata.contactsMobile,
              orgName: thisdata.orgName
            },
            this.state.RowData
          );
        }.bind(this)
      }).always(
        function() {
          this.setState({
            loading: false
          });
        }.bind(this)
      );
    },

    stopPropagation(e) {
      e.stopPropagation();
      e.nativeEvent.stopImmediatePropagation();
    },
    //删除按钮
    delete(id) {
      $.ajax({
        method: "post",
        dataType: "json",
        crossDomain: false,
        url:
          globalConfig.context + "/api/admin/customerCase/deleteCustomerCase",
        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)
      );
    },
    //项目列表整行点击
    tableRowClick(record, index) {
      this.state.RowData = record;
      this.setState({
        editvisible: true
      });
      this.edit(record);
    },

    edithandleCancel(e) {
      this.setState(
        {
          editvisible: false
        },
        () => {
          this.addReset();
        }
      );
      this.loadData();
    },

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

    add() {
      this.setState({
        editvisible: true,
        flag: false
      });
    },
    toTop(record, num) {
      this.setState({
        loading: true
      });
      $.ajax({
        method: "post",
        dataType: "json",
        crossDomain: false,
        url:
          globalConfig.context + "/api/admin/customerCase/updateCustomerCase",
        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)
      );
    },
    addNew(flag) {
      if(this.state.locations.length === 0){
        message.warning('请选择公司')
        return;
      }
      if (this.state.flag) {
        $.ajax({
          method: "post",
          dataType: "json",
          crossDomain: false,
          url:
            globalConfig.context + "/api/admin/customerCase/updateCustomerCase",
          data: {
            id: this.state.id,
            name: this.state.name,
            pictureUrl: this.state.pictureUrl
              ? this.state.pictureUrl[0].response.data
              : undefined,
            status: this.state.status ? this.state.status : 0,
            releaseStatus: flag,
            province: this.state.province,
            region: this.state.region,
            sort: this.state.sort,
            locations:this.state.locations.join(','),
          },
          success: function(data) {
            let theArr = [];
            if (data.error && data.error.length) {
              message.warning(data.error[0].message);
            } else {
              this.loadData();
              this.cancelAdd();
            }
          }.bind(this)
        }).always(
          function() {
            this.setState({
              loading: false
            });
          }.bind(this)
        );
      } else {
        $.ajax({
          method: "post",
          dataType: "json",
          crossDomain: false,
          url: globalConfig.context + "/api/admin/customerCase/addCustomerCase",
          data: {
            name: this.state.name,
            pictureUrl: this.state.pictureUrl
              ? this.state.pictureUrl[0].response.data
              : undefined,
            status: this.state.status ? this.state.status : 0,
            releaseStatus: flag,
            province: this.state.province,
            region: this.state.region,
            sort: this.state.sort,
            locations: this.state.locations.join(','),
          },
          success: function(data) {
            let theArr = [];
            if (data.error && data.error.length) {
              message.warning(data.error[0].message);
            } else {
              this.loadData();
              this.cancelAdd();
            }
          }.bind(this)
        }).always(
          function() {
            this.setState({
              loading: false
            });
          }.bind(this)
        );
      }
    },

    issueNew() {
      this.change("releaseStatus", 1, () => {
        this.addNew();
      });
    },
    //编辑按钮操作
    edit(record) {
      this.setState({
        flag: true,
        editvisible: true
      });
      this.setState({
        loading: true
      });
      $.ajax({
        method: "get",
        dataType: "json",
        crossDomain: false,
        url:
          globalConfig.context + "/api/admin/customerCase/selectCustomerCase",
        data: {
          id: record.id
        },
        success: function(data) {
          let thisdata = data.data;
          let str = "";
          if (data.error && data.error.length) {
            message.warning(data.error[0].message);
          }
          placeList.forEach(item => {
            if (item.value == thisdata.region) {
              str = item.place;
            }
          });
          this.setState({
            id: thisdata.id,
            name: thisdata.name,
            pictureUrl: thisdata.pictureUrl
              ? splitUrl(
                  thisdata.pictureUrl,
                  ",",
                  globalConfig.avatarUploadHost
                )
              : [],
            status: thisdata.status,
            releaseStatus: thisdata.releaseStatus,
            province: thisdata.province + "",
            region: thisdata.region,
            regionStr: str,
            locations: thisdata.locations,
            checked:thisdata.locations.length === companyList.length,
            indeterminate: thisdata.locations.length < companyList.length,
            sort: thisdata.sort,
            releaseTimeConvert: thisdata.releaseTimeConvert,
            createTimeConvert: thisdata.createTimeConvert
          });
        }.bind(this)
      }).always(
        function() {
          this.setState({
            loading: false
          });
        }.bind(this)
      );
    },
    cancelAdd() {
      this.setState(
        {
          editvisible: false
        },
        () => {
          this.setState({
            flag: true
          });
          this.addReset();
        }
      );
      this.loadData();
    },

    //新增框的清零
    addReset() {
      this.setState({
        name: undefined,
        pictureUrl: undefined,
        status: 0,
        province: undefined,
        region: undefined,
        sort: undefined,
        regionStr: undefined,
        locations: [],
        indeterminate: false,
        checked:false,
      });
    },
    imghandleCancel() {
      this.setState({
        imgeditvisible: false
      });
    },
    //搜索部分的清零
    reset() {
      this.setState({
        location: undefined,
        nameSearch: undefined,
      },()=>{
        this.loadData();
      })
    },
    getOrgCodeUrl(e) {
      this.setState({ pictureUrl: e });
    },

    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
        );
      }
    },

    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; //日期输入框
      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.nameSearch}
                onChange={e => {
                  this.setState({ nameSearch: e.target.value });
                }}
              />
              <Select
                  placeholder="请选择公司"
                  style={{ width: 150 }}
                  value={this.state.location}
                  onChange={e => {
                    this.setState({
                      location: e
                    });
                  }}
              >
                {
                  companyList.map((v)=>(
                      <Select.Option key={v.value} value={v.value}>{v.label}</Select.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}
                  pagination={this.state.pagination}
                  onRowClick={this.tableRowClick}
                  bordered
                  size="small"
                />
              </SpinContainer>
            </div>
          </div>
          <div className="patent-desc">
            <Modal
              className="customeDetails"
              title={this.state.flag ? "客户服务详情" : "新增案例信息"}
              width="511px"
              visible={this.state.editvisible}
              onOk={this.edithandleCancel}
              onCancel={
                this.state.flag ? this.edithandleCancel : this.cancelAdd
              }
              footer=""
            >
              <SpinContainer spinning={this.state.loading}>
                <div className="clearfix">
                  <FormItem
                    labelCol={{ span: 7 }}
                    wrapperCol={{ span: 13 }}
                    label="服务客户名称："
                  >
                    <Input
                      placeholder="请输入服务客户名称"
                      value={this.state.name}
                      onChange={e => {
                        this.setState({
                          name: e.target.value
                        });
                      }}
                      style={{ width: "140px" }}
                    />
                  </FormItem>
                </div>
                <div className="clearfix">
                  <FormItem
                    labelCol={{ span: 7 }}
                    wrapperCol={{ span: 13 }}
                    label="所属省份"
                  >
                    <Select
                      style={{ width: 120 }}
                      placeholder="请选择省份"
                      value={this.state.province}
                      onChange={e => {
                        this.setState({
                          province: e
                        });
                        let str = "";
                        provinceStatus.forEach(item => {
                          if (item.value == e) {
                            str = item.key;
                          }
                        });
                        placeList.forEach(item => {
                          item.children.forEach(key => {
                            if (key == str) {
                              this.setState({
                                regionStr: item.place,
                                region: item.value
                              });
                            }
                          });
                        });
                      }}
                    >
                      {provinceStatus.map(item => {
                        return <Option value={item.value}>{item.key}</Option>;
                      })}
                    </Select>
                  </FormItem>
                </div>
                <div className="clearfix">
                  <FormItem
                    labelCol={{ span: 7 }}
                    wrapperCol={{ span: 13 }}
                    label="所属区域"
                  >
                    <Input
                      value={this.state.regionStr}
                      disabled
                      style={{ width: "140px" }}
                    />
                  </FormItem>
                </div>
                <div className="clearfix">
                  <FormItem
                      labelCol={{ span: 7 }}
                      wrapperCol={{ span: 13 }}
                      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: 7 }}
                    wrapperCol={{ span: 13 }}
                    label="排序"
                  >
                    <Input
                      value={this.state.sort}
                      placeholder="请输入数字"
                      onChange={e => {
                        this.setState({
                          sort: e.target.value
                        });
                      }}
                      style={{ width: "140px" }}
                    />
                  </FormItem>
                </div>
                <div className="clearfix">
                  <FormItem
                    labelCol={{ span: 7 }}
                    wrapperCol={{ span: 13 }}
                    label="客户logo"
                  >
                    <PicturesWall
                      flagimg={this.state.flag}
                      fileList={this.getOrgCodeUrl}
                      pictureUrl={this.state.pictureUrl}
                    />
                    <p>建议尺寸:248X189 图片建议：要清晰。</p>
                  </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 BuyList;
