import React from 'react';
import { withRouter } from "react-router-dom";
import { Form, Input, Button, Checkbox ,Select,Modal,message} from 'antd';
import {industryList,childIndustryList} from '@/domains/store-domain/constants'
import SelectPrepareFileModal from '@/modules/prepare-lesson/modal/SelectPrepareFileModal';
import Upload from '@/core/upload';
// import PhotoClip from 'photoclip';
import StoreService from "@/domains/store-domain/storeService";
import User from "@/common/js/user";
import Bus from '@/core/tbus';
import "./StoreInfo.less";
let cutFlag = false;
class StoreInfo extends React.Component {
  formRef = React.createRef();
  constructor(props) {
    super(props);
    this.state = {
      storeName:null,
      storeFullName:null,
      subjectType:null,
      corpIndustry:null,
      corpSubIndustry:null,
      logo:'',
      showSelectFileModal:false,
      cutImageBlob: null,
    }
  }
  componentWillMount(){
    this.getStoreDetail()
  }
  getStoreDetail = ()=>{
    const params= {
      storeId:User.getStoreId()
    }
    StoreService.getStoreDetail(params).then((res) => {
      const { result = { } } = res;
      const {
        storeName,
        storeFullName,
        subjectType,
        corpIndustry,
        corpSubIndustry,
        logo
      } = result;
      this.formRef.current.setFieldsValue({
        storeName:storeName
      });
      this.formRef.current.setFieldsValue({
        storeFullName:storeFullName
      });
      this.formRef.current.setFieldsValue({
        subjectType:subjectType
      });
      this.formRef.current.setFieldsValue({
        corpIndustry:corpIndustry
      });
      this.formRef.current.setFieldsValue({
        corpSubIndustry:corpSubIndustry
      });
      this.setState({
        storeName,
        storeFullName,
        subjectType,
        corpIndustry,
        corpSubIndustry,
        logo
      })
    });
  }
  onChangeFiledValue=(filed,value)=>{
    this.setState({
      [filed]:value
    })
  }
  handleSelectCover = (file)=> {
    this.uploadImage(file);
  }
  
  //上传图片
  uploadImage = (imageFile) => {
    const { folderName } = imageFile;
    const fileName = window.random_string(16) + folderName.slice(folderName.lastIndexOf("."));
    const self = this;
    this.setState(
      {
        visible: true,
      },
      () => {
        setTimeout(() => {
          const okBtnDom = document.querySelector("#headPicModal");
          const options = {
            size: [500, 128],
            ok: okBtnDom,
            maxZoom: 3,
            style: {
              jpgFillColor: "transparent",
            },
            done: function (dataUrl) {
              clearTimeout(self.timer);
              self.timer = setTimeout(() => {
                if ((self.state.rotate != this.rotate()) || (self.state.scale != this.scale())) {
                  console.log(this.scale(), 'scale')
                  const _dataUrl = this.clip()
                  const cutImageBlob = self.convertBase64UrlToBlob(_dataUrl);
                  self.setState({
                    cutImageBlob,
                    dataUrl: _dataUrl,
                    rotate: this.rotate(),
                    scale: this.scale()
                  })
                }

              }, 500)

              const cutImageBlob = self.convertBase64UrlToBlob(dataUrl);
              self.setState({
                cutImageBlob,
                dataUrl
              })
              setTimeout(() => {
                cutFlag = false;
              }, 2000);
            },
            fail: (failInfo) => {
              message.error("图片上传失败了，请重新上传");
            },
            loadComplete: function (img) {
              setTimeout(() => {
                const _dataUrl = this.clip()
                self.setState({
                  dataUrl: _dataUrl,
                  hasImgReady: true 
                })
              }, 100)

            },
          };
          const imgUrl = `${imageFile.ossUrl}?${new Date().getTime()}`
          if (!this.state.photoclip) {
            const _photoclip = new PhotoClip("#headPicModal", options);
            _photoclip.load(imgUrl);
            this.setState({
              photoclip: _photoclip,
            });
          } else {
            this.state.photoclip.clear();
            this.state.photoclip.load(imgUrl);
          }

        }, 200);
      }
    );
  };

  //获取resourceId
  getSignature = (blob, fileName) => {
    Upload.uploadBlobToOSS(blob, 'cover' + (new Date()).valueOf(),null,'signInfo').then((signInfo) => {
      this.setState({
        coverClicpPath:signInfo.fileUrl,
        coverId:signInfo.resourceId,
        visible: false
      },()=>this.updateCover())
    
    });
  };
  updateCover = () =>{
    const {coverClicpPath,coverId} = this.state
    this.setState({
      showSelectFileModal: false
    })
    this.setState({
      logo:coverClicpPath
    })
  }
   // base64转换成blob
  convertBase64UrlToBlob = (urlData) => {
    const bytes = window.atob(urlData.split(",")[1]);
    const ab = new ArrayBuffer(bytes.length);
    const ia = new Uint8Array(ab);
    for (let i = 0; i < bytes.length; i++) {
      ia[i] = bytes.charCodeAt(i);
    }
    return new Blob([ab], { type: "image/png" });
  };
  updateInfo=()=>{
    const {storeName,storeFullName,logo,subjectType,corpIndustry,corpSubIndustry} = this.state;
    if(!storeName){
      message.warning('请输入学院简称');
     return;
    }
    if(!storeFullName){
      message.warning('请输入学院名称');
      return;
    }
    if(!subjectType){
      message.warning('请选择学院类型');
      return;
    }
    if(!corpIndustry){
      message.warning('请选择学院所属行业');
      return;
    }
    const params= {
      storeName,
      storeFullName,
      logo,
      subjectType,
      corpIndustry,
      corpSubIndustry,
      storeId:User.getStoreId()
    }
    StoreService.updateStoreMessage(params).then((res) => {
      User.setStoreName(storeName);
      Bus.trigger('storeNameChange',storeName);
      message.success('保存成功');
    });
  }
  render() {
    const {storeName,storeFullName,subjectType,corpIndustry,corpSubIndustry,showSelectFileModal,visible,hasImgReady,logo,cutImageBlob } = this.state;
    return (
      <div className="page store-info-page">
        <div className="content-header">学院基本信息</div>
        <div className="box">
          <div className="store-info-header">学院基本信息</div>
          <div className="store-info-page-form">
           
            <Form ref={this.formRef}>
              <Form.Item
                label="学院简称"
                name="storeName"
                rules={[{ required: true}]}
              >
                <Input  value={storeName} style={{ width: '300px' }} placeholder="请输入学院简称" onChange={(e)=>this.onChangeFiledValue("storeName",e.target.value)} maxLength={20}/>
              </Form.Item>
              <Form.Item
                label="学院名称"
                name="storeFullName"
                rules={[{ required: true}]}
              >
                <Input value={storeFullName} style={{ width: '300px' }} placeholder="请输入学院名称" onChange={(e)=>this.onChangeFiledValue("storeFullName",e.target.value)} maxLength={30}/>
              </Form.Item>
          
              <Form.Item
                label="学院logo"
              >
                <div className="logo-con">
                  <div className="logo-img-con">
                    { logo ?  <img src={logo}  className="logo-img"/> : <div className="logo-box"><span className="text">Logo</span></div>}
                  </div>
                  <div className="operate-con">
                    <div><span onClick={() => {this.setState({ showSelectFileModal:true  })}} className="upload-btn">
                      {logo ? <span>重新上传</span> : <span>上传</span> }
                    </span></div>
                    <div className="tip">建议尺寸702*180px。最大2M，支持jpg、jpeg和png。</div>
                  </div>  
                </div>
              </Form.Item>
              <Form.Item
                label="学院类型"
                name="subjectType"
                rules={[{ required: true }]}
              >
                <Select
                  placeholder="Select a option and change input text above"
                  allowClear
                  style={{ width: '300px' }}
                  placeholder="请选择学院类型"
                  value={subjectType}
                  onChange={(value)=>this.onChangeFiledValue("subjectType",value)}
                >
                  <Option value="COMPANY">企业</Option>
                  <Option value="INSTITUTION">政府以及事业单位</Option>
                  <Option value="ELSE">其他组织</Option>
                  <Option value="TEAM ">团队号</Option>
                </Select>
              </Form.Item>
              <Form.Item
                label="学院所属行业"
                rules={[{ required: true }]}
                name="corpIndustry"
              >
                <Select
                 placeholder="请选择学院所属行业"
                  style={{ width: '300px' }}
                  allowClear
                  value={corpIndustry}
                  onChange={(value)=>this.onChangeFiledValue("corpIndustry",value)}
                >
                  {industryList.map((item,index)=>{
                    return <Option value={item}>{item}</Option>
                  })
                  }
                  
                </Select>
              </Form.Item>
              <Form.Item
                label="学院所属子行业"
                name="corpSubIndustry"
              >
                <Select
                  placeholder="请选择学院所属子行业"
                  allowClear
                  style={{ width: '300px' }}
                  value={corpSubIndustry}
                  onChange={(value)=>this.onChangeFiledValue("corpSubIndustry",value)}
                >
                  {childIndustryList[corpIndustry] && 
                      childIndustryList[corpIndustry].map((item,index)=>{
                        return <Option value={item}>{item}</Option>
                      }) 
                  }
                </Select>
              </Form.Item>
            </Form>
          </div>
          {showSelectFileModal && 
            <SelectPrepareFileModal
              key="basic"
              operateType="select"
              multiple={false}
              accept="image/jpeg,image/png,image/jpg"
              selectTypeList={['JPG', 'JPEG', 'PNG']}
              tooltip='支持文件类型：jpg、jpeg、png'
              isOpen={showSelectFileModal}
              onClose={() => {
                this.setState({
                  showSelectFileModal:false
                })
              }}
              onSelect={this.handleSelectCover}
            />
          }
          <Modal
            title="设置图片"
            width={1080}
            visible={visible}
            maskClosable={false}
            closeIcon={<span className="icon iconfont modal-close-icon">&#xe6ef;</span>}
            onCancel={() => {
              this.setState({ visible: false });
            }}
            zIndex={10001}
            footer={[
              <Button
                key="back"
                onClick={() => {
                  this.setState({ visible: false });
                }}
              >
                重新上传
              </Button>,
              <Button
                key="submit"
                type="primary"
                disabled={!hasImgReady}
                onClick={() => {
                  if (!cutFlag) {
                    cutFlag = true;
                    this.refs.hiddenBtn.click();
                  }
                  this.getSignature(cutImageBlob);
                }}
              >
                确定
              </Button>,
            ]}
          >
            <div className="clip-box">
              <div
                id="headPicModal"
                ref="headPicModal"
                style={{
                  width: "500px",
                  height: "430px",
                  marginBottom: 0,
                }}
              ></div>
              <div id="clipBtn" style={{ display: "none" }} ref="hiddenBtn"></div>
              <div className="preview-img">
                <div className="title">效果预览</div>
                <div id="preview-url-box" style={{width:500,height:128}}>
                  <img src={this.state.dataUrl} style={{ width: '100%' }} alt="" />
                </div>
                <div className="tip-box">
                  <div className="tip">温馨提示</div>
                  <div className="tip">①预览效果图时可能存在延迟，单击左侧图片刷新即可</div>
                  <div className="tip">②设置图片时双击可旋转图片，滚动可放大或缩小图片</div>
                </div>
              </div>
            </div>
          </Modal>
          <div><Button type="primary" onClick={this.updateInfo} htmlType="submit" className="submit-btn">更新信息</Button></div>
        </div>

      </div>
    )
  }
}

export default withRouter(StoreInfo);