· 5 years ago · Dec 26, 2019, 03:58 AM
1import React, { Component } from "react";
2import { Table, Button, Icon, Modal, Switch, Popover, Tag } from "antd";
3import { connect } from "react-redux";
4import { Helmet } from "react-helmet";
5import {isWebUri} from "valid-url";
6import _ from "lodash";
7import {
8  getMarketplaceCredential,
9  getListShopeesyncmyProducts,
10  editProduct,
11  replaceExportHistoryData,
12  editShopeesyncmyProductData,
13  getShopeeCategory,
14  getShopeeShipping,
15  getShopeePromotionList
16} from "Actions";
17import {
18  API_TABLE_ROWS_PER_PAGE,
19  API_TABLE_ROWS_PER_PAGE_OPTIONS
20} from "Constants/ApiConfig";
21import IntlMessages from "Util/IntlMessages";
22import NoRecordFoundProduct from "Routes/products/products/NoRecordFoundProduct";
23import SelectRecordOptions from "./SelectRecordOptions";
24import IndexTableColumns from "./component/Index/IndexTableColumns";
25import MarketplaceChannelButton from "../component/MarketplaceChannelButton";
26import SearchPanel from "../component/SearchPanel";
27
28const confirm = Modal.confirm;
29
30class shopeesyncmy extends Component {
31  constructor(props) {
32
33    super(props);
34
35    this.type = "ShopeeMY";
36    
37    this.state = {
38      currentPage: 1,
39      data: [],
40      pagination: {
41        pageSize: API_TABLE_ROWS_PER_PAGE,
42        pageSizeOptions: API_TABLE_ROWS_PER_PAGE_OPTIONS,
43        showSizeChanger: true,
44        showQuickJumper: true,
45        className: "un-pagination-class"
46      },
47      limit: API_TABLE_ROWS_PER_PAGE,
48      selectedRowKeys: [], // Check here to configure the default column
49      productType: "",
50      filters: {},
51      sort: "-sort_order",
52      dataChanged: false,
53      deleteAll: false,
54      emptyText: <NoRecordFoundProduct {...this.props} state={this.state} />,
55      isfilterCollapsed: true,
56      displayTableHeader: true,
57      selectRecordOptions: undefined,
58      rowSelection: {},
59      exportListVisible:false,
60      shopeeinformation: {
61        shopid:28881720,
62        partnerid: 840172,
63        secretkey: "9f5ab70e25d01fbae237214f64f8541a0e0fdf30231ac740dd5b5dd50d0cf43c"   
64      }
65    };
66  }
67
68  editProduct = (event, id) => {
69    if(_.indexOf(['TD', 'IMG', 'SPAN'], event.target.tagName) >= 0) {
70      this.props.editProduct(id, this.state.productType, this.props.history);
71    }
72  };
73
74  editShopeesyncmyProduct = (event, id) => {
75    this.props.editShopeesyncmyProductData(id, this.state.productType,this.props.history);
76  };
77
78  handleChangeStoreModel = () => {
79    this.setState({changeStoreModel: !this.state.changeStoreModel});
80  };
81
82  handleDeleteStoreModel = () => {
83    this.setState({deleteStoreModel: !this.state.deleteStoreModel});
84  };
85
86  handleTableChange = (pagination, tableFilters, sorter) => {
87    this.hideSelectOptions();
88    this.setState({ limit: pagination.pageSize }, () => {
89
90      const { dataChanged, limit, productType, filters } = this.state;
91      let sort = sorter.field;
92      if (_.isEmpty(sorter)) {
93        sort = "-sort_order";
94      } else if (sorter.order == "descend") {
95        sort = "-" + sort;
96      }
97
98      this.setState({
99        pagination: pagination,
100        sort: sort,
101        dataChanged: dataChanged ? false : true
102      });
103
104      const currentPage = pagination.current;
105      this.props.getListShopeesyncmyProducts({
106        currentPage,
107        limit,
108        storeId: this.props.storeId,
109        productType: productType,
110        sort,
111        filters
112      });
113      this.setState({ selectedRowKeys: [] });
114    });
115  };
116
117  searchProducts = filters => {
118    const { limit, productType, pagination, sort } = this.state;
119
120    this.props.getListShopeesyncmyProducts({
121      currentPage: 1,
122      limit,
123      storeId: this.props.storeId,
124      productType: productType,
125      sort,
126      filters
127    });
128    this.setState({ selectedRowKeys: [], filters });
129  };
130
131  onReset = () => {
132    this.setState({ selectedRowKeys: [], filters: [] });
133  };
134
135  onSelectChange = selectedRowKeys => {
136    this.setState({ selectedRowKeys });
137  };
138
139  onSwitchChange = (id, value) => {
140    this.props.setProductStatus(id, value);
141  };
142
143  componentDidMount() {
144         console.log("2fff44");
145    //understand that there is no data at all
146    let currentChannel = _.get(this.props.currentMarketPlaceChannels, `${this.type}`, null);
147
148    // Current channel is empty, try get credential first
149    if (!currentChannel && _.isEmpty(currentChannel)) {
150        return this.props.getMarketplaceCredential(this.props.storeId, this.type);
151    }
152
153    if (this.props.newStore) {
154        this.props.addNewStore(false);
155    }
156
157    //check the category in props
158    if(!(this.props.datacat).length > 0){
159      this.props.getShopeeCategory(this.state.shopeeinformation);
160    }
161    
162    //check the shipping in props
163    if(!(this.props.dataship).length > 0){
164      this.props.getShopeeShipping(this.state.shopeeinformation);
165    }
166
167    //get shopee promotion list
168    if(!(this.props.datapromo).length > 0){
169      this.props.getShopeePromotionList(this.state.shopeeinformation);
170    }
171
172    const { limit, sort, filters } = this.state;
173
174    const warehouseID = _.get(currentChannel, 'warehouse_id', 0);
175
176    // If productList empty, but warehouseid not 0, get lazadaproduct
177    if (!_.get(this.props, 'productListData.data', false) && (this.props.storeId && warehouseID !== 0)) {
178        this.props.getListShopeesyncmyProducts({
179            currentPage: 1,
180            limit,
181            storeId: this.props.storeId,
182            warehouseID: warehouseID,
183            byStatus: this.state.syncStatus,
184            sort,
185            filters
186        });
187    }
188  }
189
190  componentDidUpdate(prevProps, prevState) {
191         console.log("222");
192    if (prevProps.allMarketPlaceChannels !== this.props.allMarketPlaceChannels) {
193        const {limit, sort, filters} = this.state;
194
195        // if warehouse_id not exists, set as 0 and redirect to setup
196        const warehouseID = _.get(this.props.currentMarketPlaceChannels, `${this.type}.warehouse_id`, 0);
197        if (this.props.storeId && warehouseID !== 0) {
198            this.props.getListShopeesyncmyProducts({
199                currentPage: 1,
200                limit,
201                storeId: this.props.storeId,
202                warehouseID: warehouseID,
203                byStatus: this.state.syncStatus,
204                sort,
205                filters,
206            });
207        } else {
208            this.props.history.push('/app/marketplace/shopeesyncmy/setup');
209        }
210    }else{
211       console.log("ss334");
212    }
213   
214    if (this.props.productList.hasOwnProperty("data")) {
215        if (this.state.data.length === 0) {
216            this.setState({
217                data: this.props.productList.data,
218                pagination: {
219                    total: this.props.productList.total,
220                    currentPage: this.props.productList.current_page,
221                    current: this.props.productList.current_page,
222                    pageSize: parseInt(this.props.productList.per_page)
223                }
224            });
225        }
226    }
227  }
228  
229  onSearchCollapseChange = (status) => {
230    let _collapseStatus = status.length === 0 ? true : false; 
231    this.setState({
232      isfilterCollapsed: _collapseStatus
233    });
234  }
235
236  hideSelectOptions = () => {
237    this.setState({
238      displayTableHeader: true,
239      selectRecordOptions: undefined
240    });
241  }
242
243  getMovePageMenu = () => {
244    let currentPage = parseInt(this.props.productList.current_page);
245    let perPage = parseInt(this.props.productList.per_page);
246    let totalRecords = parseInt(this.props.productList.total);
247    let totalPage = Math.ceil(totalRecords / perPage);
248    const items = [];
249    for (let index = 1; index <= totalPage; index++) {
250      let aClass = (index === currentPage) ? "disabled" : "";
251      items.push(
252        <li key={index}>
253          <a className={aClass}
254            onClick={(index === currentPage) ? null : this.handelMoveToPageProductsClick.bind(this, index)}
255          >
256            {index}
257          </a>
258        </li>
259      )
260    }
261    return (
262      <ul className="move-page-list">
263        {items}
264      </ul>
265    );
266  }
267
268  getMobileMenu = () => {
269    return (
270      <ul className="slection-menu-mobile">
271        
272        <Popover placement="bottom" title={<IntlMessages id="localization.moveToPage" />} content={this.getMovePageMenu()} trigger="click">
273          <li>
274            <a>
275              <IntlMessages id="localization.move" />
276              <Icon type="caret-right" rotate="90"/>
277            </a>
278          </li>
279        </Popover>
280      </ul>
281    );
282  }
283
284  displaySelectOptions = (selectedRows) => {
285    this.setState({
286      displayTableHeader: true,
287      selectRecordOptions: () => {
288        return (
289          <SelectRecordOptions {...this.props} state={this.state}
290            selectedRows={selectedRows}
291            getMobileMenu={this.getMobileMenu}
292            
293            getMovePageMenu={this.getMovePageMenu.bind(this)}
294            />
295          );
296      }
297    });
298  }
299
300  handleSelect = (record, selected, selectedRows, nativeEvent) => {
301    if (_.isEmpty(selectedRows)) {
302      this.hideSelectOptions();
303    } else {
304      this.displaySelectOptions(selectedRows);
305    }
306  }
307
308  handleSelectAll = (selected, selectedRows, changeRows) => {
309    if (selected === true) {
310      this.displaySelectOptions(selectedRows);
311    } else {
312      this.hideSelectOptions();
313    }
314  };
315
316  render() {
317
318    const { match, loading, productList, productSwitchStatus} = this.props;
319    const data = productList.data;
320    const { selectedRowKeys, productType, emptyText, isfilterCollapsed, displayTableHeader, selectRecordOptions } = this.state;
321
322    let currentChannel = _.get(this.props.currentMarketPlaceChannels, `${this.type}`, false);
323    let allChannel = _.get(this.props.allMarketPlaceChannels, `${this.type}`, false);
324    if (allChannel && currentChannel) {
325        allChannel = "";
326    }
327
328    let filterSizeClass = isfilterCollapsed ? 'col-auto' : 'col-md-12';
329
330    this.state.rowSelection = {
331      selectedRowKeys,
332      onChange: this.onSelectChange,
333      hideDefaultSelections: true,
334      onSelection: this.onSelection,
335      onSelect: this.handleSelect,
336      onSelectAll: this.handleSelectAll,
337    };
338    
339    let displayIcon = (
340      <i className="zmdi zmdi-shopping-basket mr-10 un-top-4 mb-5" />
341    );
342    let headerText = (
343      <React.Fragment>
344        <div className="pull-left">
345          <h2 style={{color: "#55ce63"}}>
346              {displayIcon}
347              <IntlMessages id="shopee.shopeemy"/> - Current Store : {(currentChannel) ?
348              <span style={{display: "inline", color: "red"}}>{currentChannel.channels.name}</span> : null}
349          </h2>       
350        </div>
351
352        <div className="pull-right">
353          <MarketplaceChannelButton
354            history={this.props.history}
355            addNewStore={this.props.addNewStore}
356            type={this.type}
357            handleChangeStoreModel={this.handleChangeStoreModel}
358            handleDeleteStoreModel={this.handleDeleteStoreModel}
359          />
360        </div>
361      </React.Fragment>
362    );
363
364    return (
365      <div className="un-page un-product p-4">
366
367        <Helmet>
368            <title>ShopeeMY Sync</title>
369            <meta
370                name="description"
371                content="ShopeeMY Marketplace Sync"
372            />
373        </Helmet>
374
375        <div className="row justify-content-between pl-3 pr-2">
376          {headerText}
377        </div>
378
379        <div className="row pt-2">
380          <div className={filterSizeClass + ' un-ant-collapse'}>
381            <SearchPanel
382              onReset={this.onReset}
383              searchProducts={this.searchProducts}
384              {...this.props}
385              stateParent={this.state}
386              onSearchCollapseChange={this.onSearchCollapseChange} />
387          </div>
388        </div>
389        <div className="row mt-3">
390          <div className="col-md-12">
391            <Table
392              className="un-block"
393              title={selectRecordOptions}
394              showHeader={displayTableHeader}
395              rowSelection={this.state.rowSelection}
396              locale={{ emptyText: emptyText }}
397              columns={IndexTableColumns({
398                          currencySymbole: this.props.currencySymbole,
399                          handleShopeesyncmyProduct: this.editShopeesyncmyProduct
400                      })}
401              rowKey={record => record.id}
402              dataSource={this.state.data}
403              pagination={this.state.pagination}
404              loading={loading}
405              onChange={this.handleTableChange}
406              rowClassName='un-cursor-pointer'
407            />
408          </div>
409        </div>
410      </div>
411    );
412  }
413}
414
415// map state to props
416const mapStateToProps = ({ authUser,shopeesyncmy,marketplace}) => {
417  const { user, storeId, currencySymbole } = authUser;
418
419  const {
420      allMarketPlaceChannels,
421      currentMarketPlaceChannels,
422      allMarketPlaceChannelsLoading,
423      newStore,
424  } = marketplace;
425
426  const { datacat,dataship,productList,productListTotal,productListCurrentPage,loading,datapromo} = shopeesyncmy;
427
428  return {
429    currencySymbole,
430    allMarketPlaceChannels,
431    currentMarketPlaceChannels,
432    allMarketPlaceChannelsLoading,
433    newStore,
434    user,
435    storeId,
436    loading,
437    productList,
438    productListCurrentPage,
439    productListTotal,
440    datacat,
441    dataship,
442    datapromo
443  };
444};
445
446export default connect(
447  mapStateToProps,
448  {
449    getMarketplaceCredential,
450    getListShopeesyncmyProducts,
451    editProduct,
452    replaceExportHistoryData,
453    editShopeesyncmyProductData,
454    getShopeeCategory,
455    getShopeeShipping,
456    getShopeePromotionList,
457    changeCurrentChannel,
458    deleteMarketplaceStore,
459    addNewStore,
460  }
461)(shopeesyncmy);