import {
  Form,
  Button,
  Input,
  Select,
  notification,
  Upload,
  Tag,
  Cascader,
  InputNumber,
  Popover,
  Divider,
} from 'antd';
import React, { Component, useState } from 'react';
import { SwapRightOutlined } from '@ant-design/icons';
import { connect } from 'umi';
import { saveAs } from 'file-saver';
import { format } from 'date-fns';
import styles from '../style.less';
import { stateList } from '../staticdata';
import { apiGoodsInfosExport } from '../service';
import { GOOD_MANAGE } from '@/../config/permission.config';

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

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

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

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

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

  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: '请选择' });
    }
  };

  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,
    });
  };

  // 导出明细
  onExportGoodsInfo = async () => {
    this.setState({
      loading: true,
    });
    const form = this.formRef?.current?.getFieldValue();
    const params = Object.assign({}, form);
    const productCategoryId = form?.productCategoryId || [];
    if (productCategoryId.length) {
      params.productCategoryId = productCategoryId[productCategoryId.length - 1] || '';
    }
    const res = await apiGoodsInfosExport(params);
    this.setState({
      loading: false,
    });
    if (res) {
      const blob = new Blob([res]);
      saveAs(blob, `商品明细-${format(new Date(), 'yyyyMMdd')}.xlsx`);
    } else {
      notification.error({ message: '下载失败' });
    }
  };

  render() {
    const { treeData, permissions, isPopMode } = this.props;
    const selectW = { width: 250 };
    const iptNumWidth = { width: 118 };
    const canEditable = permissions[GOOD_MANAGE.EDITABLE];
    const content = (
      <div>
        <Button style={{ border: 'none' }} onClick={() => this.setArea(1, 'distribution')}>
          全部商品配送区域设置
        </Button>
        <br />
        <Button style={{ border: 'none' }} onClick={() => this.setArea(0, 'distribution')}>
          勾选商品配送区域设置
        </Button>
        <br />
        <Button style={{ border: 'none' }} onClick={() => this.setArea(1, 'after')}>
          全部商品售后地址设置
        </Button>
        <br />
        <Button style={{ border: 'none' }} onClick={() => this.setArea(0, 'after')}>
          勾选商品售后地址设置
        </Button>
        <br />
        <Button style={{ border: 'none' }} onClick={() => this.checkEnableUpdateStock()}>
          勾选商品库存修改
        </Button>
      </div>
    );

    const filterOption = (input, op) => op.props.children.includes(input);
    return (
      <Form
        ref={this.formRef}
        name="horizontal_login"
        initialValues={{ productType: 1 }}
        layout="inline"
        className={styles.searchForm}
      >
        <FormItem label="SKU编码" name="skuId">
          <Input maxLength={18} showCount placeholder="请输入SKU编码" style={selectW} />
        </FormItem>
        <FormItem label="商品名称" name="skuName">
          <Input placeholder="请输入商品名称" allowClear style={selectW} />
        </FormItem>
        <FormItem label="商品类型" name="productType">
          <Select style={selectW} placeholder="请选择商品类型" onChange={this.onChangeProductType}>
            <Option value={1}>实体商品</Option>
            <Option value={4}>服务类商品</Option>
            <Option value={5}>外卖商品</Option>
          </Select>
        </FormItem>
        <FormItem label="类目" name="productCategoryId">
          <Cascader
            placeholder="请选择类目"
            style={selectW}
            showSearch
            changeOnSelect
            fieldNames={{ label: 'name', value: 'id', children: 'children' }}
            options={treeData}
          />
        </FormItem>
        {this.state.productType !== 5 && (
          <>
            <FormItem label="审核状态" name="state">
              <Select
                style={selectW}
                placeholder="请选择审核状态"
                allowClear
                filterOption={filterOption}
              >
                {stateList?.map(item => (
                  <Option key={item.value} value={item.value}>
                    {item.label}
                  </Option>
                ))}
              </Select>
            </FormItem>
            <FormItem label="供货价区间">
              <FormItem name="supplyPriceMin" className={styles.iptNumRight} noStyle>
                <InputNumber placeholder="请输入" 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="请输入"
                  onChange={this.valueMin}
                />
              </FormItem>
            </FormItem>
            <FormItem name="thirdSkuNo" label="第三方SKU编码">
              <Input placeholder="请输入第三方SKU编码" allowClear style={selectW} />
            </FormItem>
          </>
        )}
        <FormItem className={styles.queryBtn}>
          <Button onClick={() => this.handleSearch()} type="primary" className={styles.button}>
            查询
          </Button>
          <Button onClick={() => this.onReset()} className={styles.button}>
            重置
          </Button>
          {this.state.productType !== 5 && (
            <>
              <Button
                loading={this.state.loading}
                onClick={() => this.onExportGoodsInfo()}
                type="primary"
                ghost
                className={styles.button}
              >
                导出
              </Button>
              {canEditable && !isPopMode ? (
                <FormItem style={{ float: 'right' }}>
                  <Popover content={content} onVisibleChange={this.handleVisibleChange}>
                    <Button type="primary" className={styles.button}>
                      批量设置
                    </Button>
                  </Popover>
                  {this.props.selectNum > 0 && (
                    <Tag color="green">已选商品 {this.props.selectNum}</Tag>
                  )}
                </FormItem>
              ) : (
                ''
              )}
            </>
          )}
        </FormItem>
      </Form>
    );
  }
}

export default goodsManage;
