import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Card, Pagination, Table, notification, Drawer, Spin } from 'antd';
import React, { Component } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { connect } from 'dva';
import styles from '../style.less';

import { apiCategoryListType, apiProductBiddingInfo } from '../service';
import { JDSHOPID } from '../staticdata';
import { columnManage } from './staticdata';
import SearchForm from './components/SearchForm';
import UpdatePriceStock from './components/UpdatePriceStock';
import Takeaway from '../Takeaway';

import { GOOD_MANAGE } from '@/../config/permission.config';
import LocalStroage from '@/utils/localStorage';
import configApi from '@/../config/env.config';

@connect(({ SupplyPrice, menu }) => ({
  SupplyPrice,
  permissions: menu.permissions,
}))
class supplyPriceUpdate extends Component {
  state = {
    pageNo: 1,
    loading: false,
    categoryTree: [],
    pageSize: 20,
    previewVisible: false,
    createloading: false,
    productType: 1, // 商品类型
    searchValue: {}, // 搜索条件
    refresh: '', // 外卖刷新
    visibleUpdatePrice: false, // 修改价格弹窗
    skuPriceStockList: [], // 修改价格弹窗数据
    spuId: '',
    spuName: '',
  };

  currentLog = null;

  supplierId = null;

  shopList = [];

  canEditable = false;

  componentDidMount() {
    this.props.SupplyPrice.tableData = {};
    this.categoryListByType(this.state.productType);
  }

  handleSearch = page => {
    const searchValue = this.searchForm.getFieldsValue() || {};
    this.setState({ searchValue });
    if (searchValue.productType !== 5) {
      const currentPage = this.state.pageNo;
      this.setState(
        {
          pageNo: page || currentPage,
          loading: true,
        },
        () => {
          const { dispatch } = this.props;
          const { pageSize, pageNo } = this.state;
          dispatch({
            type: 'SupplyPrice/getList',
            payload: {
              pageNo,
              pageSize,
              ...searchValue,
            },
          }).finally(() => {
            this.setState({
              loading: false,
            });
          });
        },
      );
    } else {
      this.setState({
        refresh: new Date().getTime(),
        searchValue,
      });
    }
  };

  onPageChange = page => {
    this.handleSearch(page);
  };

  audit = skuId => {
    this.setState({
      previewVisible: true,
      src: `${configApi.prologueDomain}/goods/${skuId}?h=0&token=${LocalStroage.get(
        'token',
      )}&hideReport=1&time=${Date.now()}`,
    });
  };

  onPageSizeChange = (current, size) => {
    this.setState(
      {
        pageSize: size,
      },
      () => this.handleSearch(),
    );
  };

  onReset = () => {
    this.setState({
      pageNo: 1,
      pageSize: 20,
    });
    this.handleSearch();
  };

  onLoad = error => {
    if (!error) {
      notification.success({ message: '操作成功' });
      this.handleSearch();
    }
  };

  filterShopList = (list = [], isEdit) =>
    list.filter(item => isEdit || !JDSHOPID.includes(item.id));

  categoryListByType = async type => {
    try {
      const { data: categoryTree } = await apiCategoryListType(type);
      if (!categoryTree) return;
      this.setState({ categoryTree });
    } catch (e) {
      console.log(e);
    }
  };

  changeProductType = e => {
    this.setState({
      productType: e || 1,
    });
    this.categoryListByType(e);
    if (e !== 5) {
      this.handleSearch(1);
    }
  };

  // 显示更新供货价弹窗
  serviceVisbleChange = async row => {
    try {
      const { data } = await apiProductBiddingInfo({
        productId: row.spuId,
      });
      if (!data) return;
      this.setState({
        spuId: row.spuId,
        spuName: data.productName,
        skuPriceStockList: data.itemList,
        visibleUpdatePrice: true,
      });
    } catch (e) {
      console.log(e);
    }
  };

  render() {
    const {
      SupplyPrice: { tableData = {} },
      permissions,
    } = this.props;
    const { pageNo, pageSize } = this.state;
    this.canEditable = permissions[GOOD_MANAGE.EDITABLE];

    return (
      <PageHeaderWrapper>
        <Spin spinning={this.state.createloading}>
          <Card>
            <SearchForm
              handleSearch={this.handleSearch}
              onReset={this.onReset}
              onLoad={this.onLoad}
              onRef={ref => {
                this.searchForm = ref;
              }}
              treeData={this.state.categoryTree}
              shopList={this.shopList}
              checkStock={this.checkEnableUpdateStock}
              changeProductType={this.changeProductType}
              setArea={(isALL, type) => this.setArea(isALL, type)}
            />
          </Card>
          {this.state.productType === 5 ? (
            <Takeaway
              handleEdit={this.handleTakeawayEdit}
              searchValue={this.state.searchValue}
              permissions={permissions}
              refresh={this.state.refresh}
            />
          ) : (
            <>
              <Spin spinning={this.state.loading}>
                <Table
                  dataSource={tableData?.records}
                  bordered
                  columns={columnManage.call(this)}
                  rowKey={record => record.skuId}
                  pagination={false}
                  className={styles.tabletop}
                  scroll={{ x: '100%', y: 500 }}
                />
              </Spin>
              <br />
              {tableData && (
                <Pagination
                  style={{ marginBottom: 10 }}
                  onChange={this.onPageChange}
                  total={tableData.total}
                  showTotal={total => `共${total}条`}
                  current={pageNo}
                  pageSize={pageSize}
                  showSizeChanger
                  onShowSizeChange={this.onPageSizeChange}
                />
              )}

              <Drawer
                visible={this.state.previewVisible}
                width="450"
                onClose={() => {
                  this.setState({ previewVisible: false });
                }}
                title="商品预览"
                bodyStyle={{ height: '90%' }}
              >
                <iframe
                  src={this.state.src}
                  frameBorder="0"
                  height="100%"
                  width="375"
                  title="商品预览"
                ></iframe>
              </Drawer>
            </>
          )}
        </Spin>
        {this.state.visibleUpdatePrice && (
          <UpdatePriceStock
            visible={this.state.visibleUpdatePrice}
            onCancel={() => {
              this.setState({ visibleUpdatePrice: false });
            }}
            skuData={this.state.skuPriceStockList}
            productId={this.state.spuId}
            spuName={this.state.spuName}
            refresh={this.handleSearch}
          />
        )}
      </PageHeaderWrapper>
    );
  }
}

export default Form.create()(supplyPriceUpdate);
