import { Form, Button, Input, Select, notification, Cascader, InputNumber } from 'antd';
import React, { Component } from 'react';
import { SwapRightOutlined } from '@ant-design/icons';
import { connect } from 'dva';
import ImportGoodsModal from '@/components/ImportGoodsModal';
import styles from '../../style.less';
import { apiDownBiddingTemplate, apiUploadGoodsFile } from '../../service';

const FormItem = Form.Item;
const { Option } = Select;
@connect(({ goodsManage, menu }) => ({
  goodsManage,
  permissions: menu.permissions,
}))
class goodsManage extends Component {
  formRef = React.createRef();

  state = {
    productType: null,
    visibleImport: false,
  };

  componentDidMount() {
    this.props.onRef(this);
    this.handleSearch();
  }

  getFieldsValue() {
    const form = this.formRef.current;
    return form.getFieldsValue();
  }

  handleSearch = () => {
    this.props.handleSearch(1);
  };

  // 下载模版
  onDownload = () => {
    const form = this.formRef.current;
    const values = form.getFieldsValue();
    apiDownBiddingTemplate(values);
  };

  valueMin = value => {
    const { getFieldValue, setFieldsValue } = this.formRef.current;
    const minVal = getFieldValue('supplyPriceMin');
    if (minVal && minVal > value) {
      setFieldsValue({ supplyPriceMax: minVal });
    }
  };

  onReset = () => {
    const form = this.formRef.current;
    form.resetFields();
    this.props.onReset();
    this.props.changeProductType(1);
    this.setState({
      productType: 1,
    });
  };

  addSpu = () => {
    this.props.addSpu();
  };

  setArea = (isAll, type) => {
    this.props.setArea(isAll, type);
  };

  // 验证是否可以修改库存
  checkEnableUpdateStock = () => {
    if (this.props.selectNum) {
      this.props.checkStock();
    } else {
      notification.info({ message: $t('select') });
    }
  };

  onChangeProductType = (v = null) => {
    const form = this.formRef.current;
    form.setFieldsValue({
      skuId: '',
      skuName: '',
      thirdSkuNo: '',
      productCategoryId: null,
      state: null,
      supplyPriceMin: null,
      supplyPriceMax: null,
      productType: v,
    });
    this.props.changeProductType(v);
    this.setState({
      productType: v,
    });
  };

  onShowImport = importType => {
    this.setState({
      visibleImport: true,
      importType,
    });
  };

  onHideImport = () => {
    this.setState({
      visibleImport: false,
    });
  };

  // 上传文件设置
  uploadConfig = () => {
    const that = this;
    return {
      name: 'file',
      async customRequest(info) {
        that.setState({
          loading: true,
        });
        const result = await apiUploadGoodsFile(info.file);
        if (result.businessCode === '0000') {
          notification.success({ message: $t('import.success') });
        }
        that.setState({
          loading: false,
        });
      },
      accept: '.xlsx',
      showUploadList: false,
    };
  };

  render() {
    const { treeData } = this.props;
    const selectW = { width: 250 };
    const iptNumWidth = { width: 118 };

    return (
      <div>
        <Form
          ref={this.formRef}
          name="horizontal_login"
          initialValues={{ productType: 1 }}
          layout="inline"
          className={styles.searchForm}
        >
          <FormItem label={$t('sku.code')} name="skuId">
            <InputNumber placeholder={$t('enter.sku.code')} max={99999999999999999} style={selectW} />
          </FormItem>
          <FormItem label={$t('product.name')} name="skuName">
            <Input placeholder={$t('enter.product.name')} allowClear style={selectW} />
          </FormItem>
          <FormItem label={$t('product.type')} name="productType">
            <Select
              style={selectW}
              placeholder={$t('select.product.type')}
              onChange={this.onChangeProductType}
            >
              <Option value={1}>{$t('physical.goods')}</Option>
              <Option value={4}>{$t('service.products')}</Option>
              <Option value={5}>{$t('delivery.products')}</Option>
            </Select>
          </FormItem>
          <FormItem label={$t('category')} name="productCategoryId">
            <Cascader
              placeholder={$t('select.category')}
              style={selectW}
              showSearch
              changeOnSelect
              fieldNames={{ label: 'name', value: 'id', children: 'children' }}
              options={treeData}
            />
          </FormItem>
          {this.state.productType !== 5 && (
            <>
              <FormItem label={$t('supply.price.range')}>
                <FormItem name="supplyPriceMin" className={styles.iptNumRight} noStyle>
                  <InputNumber placeholder={$t('input.required')} min={0} max={999999999} style={iptNumWidth} />
                </FormItem>
                <span>
                  <SwapRightOutlined />
                </span>
                <FormItem name="supplyPriceMax" className={styles.iptNumRight} noStyle>
                  <InputNumber
                    style={iptNumWidth}
                    min={0}
                    max={999999999}
                    placeholder={$t('input.required')}
                    onChange={this.valueMin}
                  />
                </FormItem>
              </FormItem>
              <FormItem name="thirdSkuNo" label={$t('thirdparty.sku')}>
                <Input placeholder={$t('enter.thirdparty.sku')} allowClear style={selectW} />
              </FormItem>
            </>
          )}
          <FormItem className={styles.queryBtn}>
            <Button onClick={() => this.handleSearch()} type="primary" className={styles.button}>{$t('query')}</Button>
            <Button onClick={() => this.onReset()} className={styles.button}>{$t('reset')}</Button>

            <Button
              type="primary"
              className={styles.button}
              onClick={() => this.onShowImport('binding')}
            >{$t('import.products')}</Button>
            <Button onClick={() => this.onDownload()} type="link" className={styles.button}>{$t('download.template')}</Button>
          </FormItem>
        </Form>
        {this.state.visibleImport && (
          <ImportGoodsModal
            visible={this.state.visibleImport}
            importType={this.state.importType}
            onHide={this.onHideImport}
          />
        )}
      </div>
    );
  }
}

export default goodsManage;
