import {
  Form,
  Button,
  Input,
  Select,
  notification,
  Upload,
  Tag,
  Cascader,
  InputNumber,
  Popover,
  Divider,
} from 'antd';
import React, { Component, useState } from 'react';
import { connect } from 'dva';
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,
  };

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

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

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

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

  // 导出明细
  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 } = this.props;
    const selectW = { width: 250 };
    const iptNumWidth = { width: 118 };
    const that = this;
    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 uploadProps = {
    //   name: 'file',
    //   async customRequest(info) {
    //     const result = await uploadFile(info.file);
    //     if (result && result.businessCode === '0000') {
    //       that.handleSearch();
    //       notification.success({
    //         message: '操作成功',
    //       });
    //     } else {
    //       notification.warning({
    //         message: result.msg,
    //         description: (
    //           <div>
    //             {result.data?.length &&
    //               result.data.map(item => <p>{item.skuNo + item.errSkuMessage}</p>)}
    //           </div>
    //         ),
    //         duration: 6,
    //       });
    //     }
    //   },
    //   accept: '.xlsx',
    //   showUploadList: false,
    // };

    const filterOption = (input, op) => op.props.children.includes(input);
    return (
      <Form
        ref={this.formRef}
        name="horizontal_login"
        layout="inline"
        className={styles.searchForm}
      >
        <FormItem label="SKU编码" name="skuId">
          <Input placeholder="请输入SKU编码" allowClear style={selectW} />
        </FormItem>
        <FormItem label="商品名称" name="skuName">
          <Input placeholder="请输入商品名称" allowClear style={selectW} />
        </FormItem>
        <FormItem label="类目" name="productCategoryId">
          <Cascader
            placeholder="请选择类目"
            style={selectW}
            showSearch
            changeOnSelect
            fieldNames={{ label: 'name', value: 'id', children: 'children' }}
            options={treeData}
          />
        </FormItem>
        <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="请输入" style={iptNumWidth} />
          </FormItem>
          <span>--</span>
          <FormItem name="supplyPriceMax" className={styles.iptNumRight} noStyle>
            <InputNumber style={iptNumWidth} placeholder="请输入" onChange={this.valueMin} />
          </FormItem>
        </FormItem>
        <FormItem label="商品类型" name="productType">
          <Select style={selectW} placeholder="请选择商品类型">
            <Option value={1}>实体商品</Option>
            <Option value={2}>虚拟商品</Option>
            <Option value={4}>服务类商品</Option>
          </Select>
        </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()} type="primary" className={styles.button}>
            重置
          </Button>
          <Button
            loading={this.state.loading}
            onClick={() => this.onExportGoodsInfo()}
            className={styles.button}
          >
            导出
          </Button>
        </FormItem>
        {canEditable ? (
          <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>}
            {/* <Button
            className={styles.button}
            type="primary"
            icon="download"
            ghost
            onClick={() => {
              window.location.href = 'https://kdspstatic.q-gp.com/批量修改库存模板.xlsx';
            }}
          >
            模版
          </Button>
          <Upload {...uploadProps}>
            <Button type="primary" className={styles.button}>
              批量库存修改
            </Button>
          </Upload> */}
          </FormItem>
        ) : (
          ''
        )}
      </Form>
    );
  }
}

export default goodsManage;
