import { connect } from 'dva/index';
import React, { Component, Fragment } from 'react';
import { Form, Spin, Alert ,Row, Col,Tree,Button ,Select,DatePicker,Input    } from 'antd';
const TreeNode = Tree.TreeNode;
const Option = Select.Option;
const RangePicker = DatePicker.RangePicker;

import {
  sldIconBtn,
  failTip,
  sucTip,
  sldSearchValClear,
  list_com_page_size_20,
  formItemLayoutModal,
  sldPopConfirmDiy,
  getTableNum,
  sldComLanguage,
  sldtbaleOpeBtnText,
  dragSldTableColumn,
  sldHandlePaginationData,
  getSldComImg,
  showMoreHelpTip,
  getSldEmptyH,
  getSldComShowMoreTtex, sldPopConfirm, dateFormat, getSldListGoodsImg80ByMedia,
} from '@/utils/utils';
import mediaCss from './media.less';
import StandardTable from '@/components/StandardTable';
import SldModal from '@/components/SldModal/SldModal';
import SldPreviewImg from '@/components/SldPreviewImg/SldPreviewImg';
import { apiUrl } from '@/utils/sldconfig.js';
import SldComHeader from '@/components/SldComHeader';
import global from "@/global.less";
import Search from "@/components/Search/Search";
import styles from "@/pages/goods/product.less";
import defaultSettings from "@/defaultSettings";

let pageSize = list_com_page_size_20;
@connect(({ store }) => ({
  store,
}))
@Form.create()



export default class mediaLists extends Component {

  constructor(props) {
    super(props);
    this.state = {
      initLoading: false,
      modalVisible: false,//是否显示规格弹框
      submiting: false,
      show_preview_modal: false,//预览图片modal框是否展示
      preview_img: '',//预览图片
      preview_alt_con: '',//预览图片内容
      modal_width: 500,
      data: {},//列表数据
      selectedRows: [],
      selectedRowKeys: [],//selectedRows的key
      operateData: [
        {
          type: 'input',
          label: `${sldComLanguage('资源名称')}`,
          name: 'name',
          placeholder: `${sldComLanguage('请输入资源名称')}`,
          extra: `${sldComLanguage('最多输入20个字')}`,
          maxLength:20,
          rules: [{
            required: true,
            whitespace: true,
            message: `${sldComLanguage('请输入资源名称')}`,
          }],
          initialValue: '',
        },
        {
          type: 'select',
          label: `${sldComLanguage('资源分类')}`,
          name: 'type',
          allowClear:true,
          is_show:'undefined_init',
          extra: `${sldComLanguage('请根据资源类型选择合适的分类')}`,
          placeholder: `${sldComLanguage('请选择')}${sldComLanguage('分类')}`,
          sel_data: [
            { key: '', name: `全部` },
            {key: 'goods', name: `${sldComLanguage('商品图片')}`},
            {key: 'video', name: `${sldComLanguage('商品视频')}`},
            {key: 'sellerBrand  ', name: `${sldComLanguage('商家申请品牌')}`},
            {key: 'certificate', name: `${sldComLanguage('店铺荣誉资质图片')}`},
            {key: 'companyShow', name: `${sldComLanguage('店铺工厂图片')}`},
            {key: 'profile', name: `${sldComLanguage('店铺简介图片')}`},
            {key: 'file', name: `${sldComLanguage('文件')}`},
          ],
          rules: [{
            required: true,
            whitespace: true,
            message: `${sldComLanguage('请选择多媒体分类')}`,
          }],
          initialValue:'',
          sldChange: (info) => this.sldChange(info,),
        },
        {
          type: 'upload_file_all',
          label: `${sldComLanguage('资源路径')}`,
          name: 'path',
          show:true,
          extra: `${sldComLanguage('图片不大于5M')}`,
          fileList: [],
          img_info: {},
          upload_name: 'file',
          required: true,
          upload_url: apiUrl + `v3/oss/common/upload?source=media`,
          getAction: (info) => this.getAction(),
          uploadPreview: this.uploadImgPreModel,
          uploadChange: (info) => this.uploadImgModal(info, 'path'),
          beforeUpload: (info) => this.beforeUpload(info),
          initialValue: '',
          rules: [{
            required: true,
            message: `${sldComLanguage('请输入资源路径')}`,
          }],
        }
      ],
      defaultExpandAll:true,
      params: { pageSize: pageSize },//搜索条件
      formValues: {},//搜索条件
      search_data: [
        {
        type: 'select',
        label: `${sldComLanguage('多媒体分类')}`,
        name: 'type',
        placeholder: `${sldComLanguage('请选择多媒体分类')}`,
        sel_data: [
          { key: '', name: `全部` },
          { key: 'goods', name: `${sldComLanguage('商品')}` },
          { key: 'sellerBrand', name: `${sldComLanguage('品牌')}` },
          { key: 'profile', name: `${sldComLanguage('店铺简介')}` },
          { key: 'companyShow', name: `${sldComLanguage('店铺展示')}` },
          { key: 'certificate', name: `${sldComLanguage('荣誉资质')}` },
          { key: 'video', name: `${sldComLanguage('视频')}` },
          { key: 'file', name: `${sldComLanguage('文件')}` },
        ],
        initialValue:''
      }, {
        type: 'select',
        label: `${sldComLanguage('文件类型')}`,
        name: 'fileType',
        placeholder: `${sldComLanguage('请选择文件类型')}`,
        sel_data: [
          { key: '', name: `${sldComLanguage('全部')}` },
          { key: 'picture', name: `${sldComLanguage('图片')}` },
          { key: 'video', name: `${sldComLanguage('视频')}` },
          { key: 'file', name: `${sldComLanguage('文件')}` },
        ],
      }, {
        type: 'rangepicker',
        label: `${sldComLanguage('日期范围')}`,
        name: 'search_create_time',
        placeholder1: `${sldComLanguage('开始时间')}`,
        placeholder2: `${sldComLanguage('结束时间')}`,
      },{
        type: 'input',
        label: `${sldComLanguage('文件名')}`,
        name: 'name',
        placeholder: `${sldComLanguage('请输入文件名')}`,
      }
      ],
      columns: [
        {
          title: `${sldComLanguage('序号')}`,
          align: 'center',
          dataIndex: 'receiveId',
          width: 30,
          render: (text, record, index) => getTableNum(this.state.params, pageSize, index),
        },
        {
          title: `${sldComLanguage('文件')}`,
          dataIndex: 'name',
          align: 'center',
          width: 200,

        },
        {
          title: `${sldComLanguage('上传人')}`,
          dataIndex: 'tplTypeName',
          align: 'center',
          width: 100,
        },
        {
          title: `${sldComLanguage('类型')}`,
          dataIndex: 'fileType',
          align: 'center',
          width: 100,
          render: (text, record) => {
            return <div className={`${mediaCss.goods_info} `}>
              {(text == '.zip' )&&<span >压缩包<a className={'action'} onClick={this.tableAction.bind(this, record)} >下载</a></span>}
              {(text == '.pdf' )&&<span >PDF文档<a className={'action'} onClick={this.tableAction.bind(this, record)} >预览</a></span>}
              {(text == '.mp4' )&&<span >视频<a className={'action'} onClick={this.tableAction.bind(this, record)}>查看</a></span>}
              {(record.fileType == 'video' )&&<span >视频<a className={'action'} onClick={this.tableAction.bind(this, record)}>查看</a></span>}
              {(text == '.docx' )&&<span >doc文档<a className={'action'} onClick={this.tableAction.bind(this, record)}>下载</a></span>}
              {(record.fileType == '.jpg' || record.fileType == '.png' || record.fileType == '.jpeg')&&<div onClick={this.tableAction.bind(this, record)}>{getSldListGoodsImg80ByMedia(record.url)}</div>}
            </div>;
          },
        },
        {
          title: `${sldComLanguage('上传时间')}`,
          dataIndex: 'createTime',
          align: 'center',
          width: 100,
        },
        {
          title: `${sldComLanguage('更新时间')}`,
          dataIndex: 'updateTime',
          align: 'center',
          width: 100,
        },
        {
          title: `${sldComLanguage('操作')}`,
          align: 'center',
          width: 100,
          render: (text, record, index) => (
            <Fragment>
              {sldtbaleOpeBtnText(`${sldComLanguage('编辑')}`, () => this.editSource(record))}
              {/*删除后不可恢复，是否确定删除？*/}
              {sldPopConfirmDiy('leftBottom', `${sldComLanguage('删除后不可恢复，是否确定删除')}`, () => this.operateGoods({mediaIds:record.id}, 'del'), `${sldComLanguage('确定')}`, `${sldComLanguage('取消')}`,
                sldtbaleOpeBtnText(`${sldComLanguage('删除')}`, () => null))}
            </Fragment>
          ),
        },
      ],
      defaultSelectedKeys:['goods'],
      defaultCheckedKeys:['goods'],
      treeData:[],
      selectedKeys:[],
      modalType:'add'
    };
  }

  currentValue = ''
  componentDidMount() {
    this.get_list({ pageSize: pageSize });
    this.get_tree()
  }

  //选择弹窗的分类给一个类型赋值
  sldChange = (val) => {
    const {operateData} = this.state
    if(val == 'video'){
      operateData[2].type = 'input'
      operateData[2].placeholder = `${sldComLanguage('请输入资源路径')}`,
      operateData[2].extra = '请输入资源路径'
    }else{
      operateData[2].type = 'upload_file_all'
      operateData[2].placeholder = `${sldComLanguage('图片不大于5M')}`,
      operateData[2].extra = '图片不大于5M'
    }
   this.currentValue = val
  }

  //上传前判断是否选择了分类
  beforeUpload = (val) => {
    if(this.currentValue == ''){
      failTip('请先选择分类')
      return false
    }
  }

  //获取上传地址
  getAction = () => {
    return  apiUrl + `v3/oss/common/upload?source=media&mediaType=` + this.currentValue
  }

  //表格的资源种类处理
  tableAction = (record) => {
    let type = record.fileType
    let url = record.url
    window.open(url)
  }

  //编辑新增 弹窗上传图片
  uploadImgModal = (info, type) => {
    console.log(info,type)
    let { operateData } = this.state;
    if(info.file.status!=undefined&&info.file.status!='error') {
        for (let i in operateData) {
          if (operateData[i].name == type) {
            operateData[i].fileList = info.fileList;
            operateData[i].img_info = (info.file.response != undefined && info.fileList.length > 0 && info.file.response.data != undefined) ? info.file.response.data : [];
          }
        }
        this.setState({ operateData });
    }
  };
  //编辑新增 弹窗预览图片
  uploadImgPreModel = (info) => {
    let img = '';
    if(info.response!=undefined&&info.response.data!=undefined){
      img = info.response.data.url;
    }else{
      img = info.url;
    }
    this.viewImg(true, img);
  };

  //预览图片/关闭预览图片
  viewImg = (flag, img = '', text = '') => {
    this.setState({
      preview_img: img,
      preview_alt_con: text,
      show_preview_modal: flag,
    });
  };

  //获取数据列表
  get_list = (params) => {
    this.setState({ initLoading: true });
    const { dispatch } = this.props;
    dispatch({
      type: 'store/get_media_list',
      payload: params,
      callback: (res) => {
        this.setState({ initLoading: false });
        if (res.state == 200) {
          this.setState({ data: res.data });
        }
      },
    });
  };

  //获取左侧树形菜单
  get_tree = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'store/get_media_menu_tree',
      callback: (res) => {
        if (res.state == 200) {
           this.setState({treeData:res.data})
        }
      },
    });
  };

  //搜索事件
  search = (data) => {
    const values = { ...data };
    //时间处理
    if (values.search_create_time) {
      values.startTime = values.search_create_time[0] ? values.search_create_time[0].format(dateFormat) + ' 00:00:00' : '';
      values.endTime = values.search_create_time[1] ? values.search_create_time[1].format(dateFormat) + ' 23:59:59' : '';
      values.search_create_time = '';
    }
    for (let i in values) {
      if (values[i] == '') {
        delete values[i];
      }
    }

    this.setState({
      formValues: values,
      selectedKeys: [values.type],
      params: { pageSize: pageSize },
    });
    this.get_list({ pageSize: pageSize, ...values });
  };

  //搜索重置事件
  seaReset = () => {
    //搜索条件置为空
    this.setState({
      formValues: {},
      selectedKeys: [],
      params: { pageSize: pageSize },
    });
    this.get_list({ pageSize: pageSize });
  };


  //树菜单操作

  onSelect = (info) =>  {
    this.setState({
      selectedKeys: info,
    });
    this.get_list({ pageSize: pageSize, ...{type:info[0]} });
  };


  //表格多选操作
  handleSelectRows = (rows, rowkeys) => {
    this.setState({
      selectedRows: rows,
      selectedRowKeys: rowkeys,
    });
  };

  handleTablePagination = (pagination, filtersArg, sorter, type = 'main') => {
    const { formValues } = this.state;
    if (type == 'main') {
      const params = sldHandlePaginationData(pagination, filtersArg, sorter, formValues);
      pageSize = params.pageSize;
      this.setState({ params });
      this.get_list(params);
    }
  };

  //表格拖动
  resizeTable = (index, size, type, data) => {
    let datas = dragSldTableColumn(index, size, data);
    this.setState({ [type]: datas });
  };

  //上传资源弹窗
  sldHandleConfirm = (val) => {
    const {operateData,modalType} = this.state
    if(this.currentValue != 'video' && val.type != 'video'){
      for (let i in operateData) {
        if ((operateData[i].name == 'path') && operateData[i].show) {
          if (operateData[i].img_info.path == undefined) {
            failTip(`${sldComLanguage('请上传图片')}`);
            return false;
          } else {
            val.path = operateData[i].img_info.path;
          }
        }
      }
      if(val.path){
        let a = val.path.split('/')
        let b = a[a.length -1]
        let c = b.split('.')
        let d = '.'+c[c.length - 1]
        val.extend = d
      }
    }else{
      val.extend = 'video'
    }
    if (modalType == 'edit') {
      val.id = this.cur_edit_id;
      this.operateGoods(val,'edit');
    } else{
      delete val.id
      this.operateGoods(val,'add');
    }
  };

  cur_edit_id = '';//当前操作数据id

  //编辑资源
  editSource = (val) => {
    const {operateData} = this.state
    this.cur_edit_id = val.id;//当前操作数据id
    console.log(val)
    if( val.type == 'video'){
      operateData[2].type = 'input'
      operateData[2].placeholder = `${sldComLanguage('请输入资源路径')}`,
      operateData[2].extra = '请输入资源路径'
    }else{
      operateData[2].type = 'upload_file_all'
      operateData[2].placeholder = `${sldComLanguage('图片不大于5M')}`,
      operateData[2].extra = '图片不大于5M'
    }
    console.log(operateData)
    for (let i in operateData) {
      if (operateData[i].type == 'upload_file_all') {
        let fileList = [];
        let tmp_data = {};
        tmp_data.uid = val.id;
        tmp_data.name = val.name;
        tmp_data.status = 'done';
        tmp_data.url = val.url;
        fileList.push(tmp_data);
        operateData[i].fileList = fileList;
        operateData[i].img_info.path = val.path
      }else if (operateData[i].name == 'name') {
        operateData[i].initialValue = val.name
      }else if (operateData[i].name == 'type') {
        operateData[i].initialValue = val.type
      }else if (operateData[i].name == 'path') {
        operateData[i].initialValue = val.path
      }
    }
    this.setState({ modalType:'edit', operateData: operateData, modalVisible: true });
  }

  openModal = () => {
    const {operateData,selectedKeys} = this.state
    //恢复默认图片的上传
    operateData[2].type = 'upload_file_all'
    operateData[2].placeholder = `${sldComLanguage('图片不大于5M')}`,
    operateData[2].extra = '图片不大于5M'
    for (let i in operateData) {
      if (operateData[i].type == 'upload_file_all') {
        operateData[i].fileList = [];
        operateData[i].img_info = {};
      }
      operateData[i].initialValue = ''
    }

    this.setState({ modalType:'add',modalVisible: true });
  }

  sldHandleCancle = () => {
    this.setState({ modalVisible: false });
  };


  operateGoods = (val,type) => {
    const {modalType} = this.state
    this.setState({ submiting: true });
    const { params,selectedKeys } = this.state;
    const { dispatch } = this.props;
    let param_data = {};
    let dis_type = '';
    if (type == 'add') {
      dis_type = 'store/get_media_info_add';
    }
    if (type == 'edit') {
      dis_type = 'store/get_media_info_edit';
    }
    if (type == 'del') {
      dis_type = 'store/get_media_info_del';
    }
    param_data = val;
    dispatch({
      type: dis_type,
      payload: param_data,
      callback: (res) => {
        this.setState({ submiting: false });
        if (res.state == 200) {
          sucTip(res.msg);
          this.get_list({params,...{type:selectedKeys[0]}});
          this.setState({
            selectedRows: [],
            selectedRowKeys: [],
            modalVisible: false,
          });
        } else {
          failTip(res.msg);
        }
      },
    });
  };


  render() {
    const { modalVisible,submiting, preview_img,show_preview_modal,operateData,selectedRows,preview_alt_con, selectedRowKeys,columns, initLoading, data,search_data ,modal_width} = this.state;

    const loop = data => data.map((item) => {
      if (item.nodeList) {
        return <TreeNode title={item.name} key={item.attribute}>{loop(item.nodeList)}</TreeNode>;
      }
      return <TreeNode title={item.name} key={item.attribute}  />;
    });
    const treeNodes = loop(this.state.treeData);

    return (
      <div style={{ flex: 1 ,padding: 10}}>
        <SldComHeader
          type={1}
          title={`${sldComLanguage('多媒体管理')}`}//品牌管理
        />
        {getSldEmptyH(10)}

          <div className={mediaCss.wrap}>
            <Row gutter={16} >
              <Col className="gutter-row" span={3}>
                <div className={mediaCss.left}>
                  <Tree className="myCls" showLine
                        defaultSelectedKeys={this.state.defaultSelectedKeys}
                        defaultCheckedKeys={this.state.defaultCheckedKeys}
                        defaultExpandAll={this.state.defaultExpandAll}
                        autoExpandParent={this.state.defaultExpandAll}
                        selectedKeys={this.state.selectedKeys}
                        onSelect={this.onSelect}
                  >
                    {treeNodes}
                  </Tree>
                </div>
              </Col>

              <Col className="gutter-row" span={21}>
                <div className={mediaCss.right}>
                  <div className={mediaCss.addBtnWrap}>
                    <Button type="primary" onClick={this.openModal}>添加新文件</Button>
                  </div>

                  <div className={global.tableListForm}>
                    <Search search_data={search_data}
                            seaSubmit={(data) => this.search(data)} seaReset={() => this.seaReset()}/>
                  </div>

                  {/*公共功能条-start*/}
                  <div className={global.operate_bg}
                       style={{ display: 'flex', flexDirection: 'row', justifyContent: 'space-between' }}>
                    <div style={{ display: 'flex', flexDirection: 'row' }}>
                      {selectedRowKeys.length == 0 ? sldIconBtn(() => {
                        failTip(`${sldComLanguage('请先选中数据')}`);
                        //确认删除选中的消息吗？
                      }, `${sldComLanguage('批量删除')}`, 7, 0, 15, 15, 3, 'shenhejujue', '#fa0920') : sldPopConfirm('leftBottom', `${sldComLanguage('确认删除选中的消息吗？')}`, () => this.operateGoods({ mediaIds: selectedRowKeys.join(',') }, 'del'), `${sldComLanguage('确定')}`, `${sldComLanguage('取消')}`, sldIconBtn(null, `${sldComLanguage('批量删除')}`, 7, 0, 15, 15, 3, 'shenhejujue', '#fa0920'), 0, 0, '#fa0920')}
                    </div>
                  </div>
                  {/*公共功能条-end*/}
                  <Spin spinning={initLoading}>
                    {/*标准表格-start*/}
                    <StandardTable
                      totalHeight={document.body.clientHeight - 200}
                      bordered={false}
                      selectedRows={selectedRows}
                      data={data}
                      rowKey={'id'}
                      isCheck={true}
                      columns={columns}
                      onSelectRow={this.handleSelectRows}
                      onChange={(pagination, filtersArg, sorter) => this.handleTablePagination(pagination, filtersArg, sorter, 'main')}
                      onSldHandleSeleRow={this.onSldHandleSeleRow}
                      resizeTable={(index, size) => this.resizeTable(index, size, 'columns', columns)}
                      isColumnResize={true}
                    />
                    {/*标准表格-end*/}
                  </Spin>
                </div>
              </Col>
            </Row>
          </div>

        { /*新增/编辑对话框-start*/}
        <SldModal
          width={modal_width}
          title={'上传资源'}
          submiting={submiting}
          modalVisible={modalVisible}
          sldHandleConfirm={(val) => this.sldHandleConfirm(val)}
          sldHandleCancle={this.sldHandleCancle}
          formItemLayoutModal={formItemLayoutModal}
          content={operateData}
        />
        { /*新增/编辑对话框-end*/}

        {/*图片预览-start*/}
        <SldPreviewImg img={preview_img} show_preview_modal={show_preview_modal} modal_width={300}
                       preview_alt_con={preview_alt_con} closePreviewModal={() => this.viewImg(false)}/>
        {/*图片预览-end*/}



      </div>

    );
  }
}
