import { PlusOutlined, UploadOutlined } from '@ant-design/icons';
import { Button, Card, message, Steps, Empty, Form, Input, Upload, Select, InputNumber, Switch } from 'antd';
import { GridContent, PageContainer, RouteContext } from '@ant-design/pro-layout';
import React, { Fragment, useRef, useState, useEffect } from 'react';
import classNames from 'classnames';
import ProTable from '@ant-design/pro-table';
import GoodsbomFrom from './components/GoodsbomFrom';
import { addGoods, goodsType, goodsbigType, getgoodsTaste } from '../newgoods/service';
import { GetGoodsBom, AddBomApi, DelGoodsBom, GetCosRequestURL, unitList } from './service'
import axios from 'axios';
const { Step } = Steps;
const { Option, OptGroup } = Select;
const Advanced = (props) => {
  console.log("调试",props);
  const [form] = Form.useForm();
  const [goodsTypes, setGoodsTypes] = useState([]);
  const [goodsUnit, setGoodsUnit] = useState([]);
  const [goodsBigTypes, setGoodsBigTypes] = useState([]);
  const [goodsTaste, setGoodsTaste] = useState([]);
  const [setGoodsBomModalVisible, handleGoodsBomModalVisible] = useState();
  const [selectedRowsState, setSelectedRows] = useState([]);
  const actionRef = useRef();
  const [currTabKey, SetCurrTabKey] = useState("basis")
  const [url, setUrl] = useState(props.location.query.values ? props.location.query.values.imgUrl : null);
  const [currentGoodsProp, setCurrentGoodsProp] = useState(0);
  //事件
  const onFinish = async (values) => {
    const hide = message.loading('正在添加');
    try {
      if(props.location.query.isAdd)values.id=null;
      values.imgUrl = url ? url : values.imgUrl;
      await addGoods(JSON.stringify(values)).then((r) => {
        if (r.data) {
          message.success('添加成功');
        } else {
          message.error('添加失败请重试！');
        }
      });
      hide();
      return true;
    } catch (error) {
      hide();
      message.error('添加失败请重试！');
      return false;
    }
  };
  const uploadProp = {
    name: 'file',
    showUploadList: false,
    multiple: false,
    accept: '.png, .jpg, .jpeg, .gif',
    // 这里需要指定文件上传的content-type
    headers: {
      'Content-Type': 'application/octet-stream',
    },
    customRequest({
      action,
      file,
      headers,
      onError,
      onProgress,
      onSuccess,
      withCredentials,
    }) {

      console.log("上传图片", file);
      //覆盖action 上传之前获取上传地址
      var index = file.name.lastIndexOf(".");
      var ext = file.name.substr(index + 1);

      let fileData = null;
      GetCosRequestURL({ directory: "goods", fileExtension: ext, method: "PUT" }).then((r) => {
        action = r.allUrl;
        const reader = new FileReader();
        reader.readAsArrayBuffer(file);
        reader.onload = (e) => {
          //console.log("fdasa","fdsafdsfdsafd");
          // 在文件读取结束后执行的操作
          fileData = e.target.result;
          // 使用 axios 进行文件上传的请求
          axios.put(action, fileData, {
            withCredentials,
            headers,
            onUploadProgress: ({ total, loaded }) => {
              // 进行上传进度输出，更加直观
              onProgress({ percent: Math.round(loaded / total * 100).toFixed(2) }, file);
            },
          }).then(response => {
            console.log('onSuccess', response, file);
            if (response.status == 200 || response.statusText == 'OK') {
              setUrl(r.seeUrl)
            }
            // onSuccess(response, file);
          })
            .catch(onError);
        };
      });
      return {
        abort() {
          console.log('upload progress is aborted.');
        },
      };
    },
    //defaultFileList: props.location.query.values ? props.location.query.values : null

  };
  //设置
  const [tabStatus, seTabStatus] = useState({
    operationKey: props.location.query.tabStatus ? props.location.query.tabStatus : 'basis',
    tabActiveKey: props.location.query.tabStatus ? props.location.query.tabStatus : 'basis',
  });
  useEffect(() => {
    SetCurrTabKey(tabStatus.tabActiveKey);
  }, [tabStatus])
  const onTabChange = (key) => {
    if (currentGoodsProp === 1) {
      message.info('套餐不能设置配方');
      return;
    }
    seTabStatus({ operationKey: key, tabActiveKey: key });
  };

  const operationTabList = [
    {
      key: 'basis',
      tab: '商品基础信息',
    },
    {
      key: 'goodsbom',
      tab: '商品配方',
    },
    // {
    //   key: 'goodspack',
    //   tab: '套餐商品',
    // },
  ];

  const bomcolumns =
    [
      {
        title: '主键',
        dataIndex: 'id',
        key: 'id',
        hideInTable: true,
        hideInSearch: true,
        tip: '规则名称是唯一的 key',
      },
      {
        title: '配方名称',
        key: 'name',
        dataIndex: 'name',
        valueType: 'textarea',
      },
      {
        title: '配方类型',
        dataIndex: 'isMain',
        hideInForm: true,
        valueEnum: {
          false: {
            text: '辅料',
            status: 'Processing',
          },
          true: {
            text: '主料',
            status: 'Success',
          },
        },
      },
      {
        title: '操作',
        dataIndex: 'option',
        valueType: 'option',
        render: (_, record) => [
          <a
            key="primary"
            type="primary"
            onClick={() => {
              const hide = message.loading('正在删除');
              try {
                DelGoodsBom(record.id);
                hide();
                message.success('删除成功，即将刷新');
                actionRef.current.reload();
                return true;
              } catch (error) {
                hide();
                message.error('删除失败，请重试');
                actionRef.current.reload();
                return false;
              }

            }}
          >
            删除
          </a>
        ],
      }
    ]

  const contentList = {
    basis: (
      <Card
        title="商品基础信息"
        style={{
          marginBottom: 24,
        }}
        bordered={false}
      >
        <Form
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 6 }}
          layout="horizontal"
          preserve={false}
          initialValues={props.location.query.values}
          onFinish={onFinish}
        >
          <Form.Item name="id" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item name="code" label="商品编码" hidden={true}   >
            <Input  disabled/>
          </Form.Item>
          <Form.Item name="name" label="商品名称" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item name="goodsUintId" label="商品单位" rules={[{ required: true }]}>
            <Select>
              {
                goodsUnit == undefined ? '' : (
                  goodsUnit.map((item, index) => {
                    return (
                      <Select.Option index={index} value={item.id} key={item.id}>
                        {item.name}
                      </Select.Option>
                    );
                  })
                )
              }
            </Select>
          </Form.Item>
          <Form.Item name="price" label="商品价格" rules={[{ required: true }]}>
            <InputNumber placeholder="价格" min={0} />
          </Form.Item>
          <Form.Item name="vipPrice" label="会员价格">
            <InputNumber placeholder="会员价" min={0} />
          </Form.Item>
          <Form.Item name="parentTypeID" label="商品大类" rules={[{ required: true }]}>
            <Select>
              {
                goodsBigTypes == undefined ? '' : (
                  goodsBigTypes.map((item, index) => {
                    return (
                      <Select.Option index={index} value={item.id} key={item.id}>
                        {item.name}
                      </Select.Option>
                    );
                  })
                )
              }
            </Select>
          </Form.Item>
          <Form.Item name="goodsTypeId" label="商品小类" rules={[{ required: true }]}>
            <Select>
              {
                goodsTypes == undefined ? '' : (
                  goodsTypes.map((item, index) => {
                    return (
                      <Select.Option index={index} value={item.id} key={item.id}>
                        {item.goodsType_Name}
                      </Select.Option>
                    );
                  })
                )
              }
            </Select>
          </Form.Item>
          <Form.Item
            name="goodsAttribute"
            label="商品属性"
            defaultValue={0}
            rules={[{ required: true, message: '请选择商品属性' }]}
          >
            <Select placeholder="请选择商品属性" onChange={(e) => {
              setCurrentGoodsProp(e);
            }}>
              <OptGroup>
                <Select.Option value={0}>单品</Select.Option>
                <Select.Option value={1}>套餐</Select.Option>
              </OptGroup>
            </Select>
          </Form.Item>
          <Form.Item
            name="status"
            label="状态"
            defaultValue={0}
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Select placeholder="请选择状态">
              <OptGroup>
                <Select.Option value={0}>正常</Select.Option>
                <Select.Option value={1}>停用</Select.Option>
              </OptGroup>
            </Select>
          </Form.Item>
          <Form.Item name="remark" label="备注">
            <Input />
          </Form.Item>
          <Form.Item name="imgUrl" hidden={true}  >
            <Input />
          </Form.Item>
          <Form.Item name="imgUrl1" label="商品图片地址"
          >
            <Upload
              {...uploadProp}
            >

              {url ? <img src={url} alt="avatar" style={{ width: '100%' }} /> : <Button icon={<UploadOutlined />}>上传</Button>}

            </Upload>
          </Form.Item>

          <Form.Item label="是否称重" name="isWeigh" valuePropName="checked" initialValue='false' >
            <Switch checkedChildren="是" unCheckedChildren="否" defaultChecked='false' />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit">
              保存
            </Button>
          </Form.Item>
        </Form>
      </Card>
    ),
    goodsbom: (
      <Card
        title="商品配方"
        style={{
          marginBottom: 24,
        }}
        bordered={false}
      >
        <ProTable
          columns={bomcolumns}
          actionRef={actionRef}
          rowKey="id"
          search={false}
          toolBarRender={() => [
            <Button
              type="primary"
              key="primary"
              onClick={() => {
                if (props.location.query.values.id == undefined || props.location.query.values.id == null) {
                  message.info('请先添加商品基础信息!');
                } else {
                  handleGoodsBomModalVisible(true);
                }
                //
              }}
            >
              <PlusOutlined /> 选择配方
            </Button>,
          ]}
          request={async (params) => {
            if (props.location.query.values.id == undefined || props.location.query.values.id == null) {

            } else {
              params.GoodsId = props.location.query.values.id;
              var total = 0;
              const msg = await GetGoodsBom(params);
              return {
                data: msg.data.data,
                success: true,
                total: total,
              };
            }

          }}
          rowSelection={{
            onChange: (_, selectedRows) => setSelectedRows(selectedRows),
          }}

        />
        <GoodsbomFrom
          onFinish={async (value) => {
            console.log("value", value);
            value['GoodsId'] = props.location.query.values.id;
            var success = false;
            success = await AddBomApi(value);
            if (success) {
              handleGoodsBomModalVisible(false);
            }
            actionRef.current.reload();
          }}
          onCancel={() => {
            handleGoodsBomModalVisible(false);
          }}
          createModalVisible={setGoodsBomModalVisible}
        />
      </Card>
    ),
  };

  //初始化
  useEffect(() => {
    function initGoodsType() {
      goodsType({ current: 1, status: 0, pageSize: 1000 }).then((r) => {
        var arr = r.data.data;
        arr.forEach((element) => {
          element.text = element.goodsType_Name;
        });

        setGoodsTypes(arr);
      });
    }
    function initGoodsBigType() {
      goodsbigType({ current: 1, status: 0, pageSize: 1000 }).then((r) => {
        var arr = r.data.data;
        arr.forEach((element) => {
          element.text = element.name;
        });

        setGoodsBigTypes(arr);
      });
    }
    function initGoodsUnit() {
      unitList('{"current":1,"pageSize":200}').then((r) => {
        var arr = r.data.data;

        setGoodsUnit(arr);
      });
    }
    initGoodsUnit();
    initGoodsType();
    initGoodsBigType();
  }, []);

  return (
    <PageContainer
      title={props.location.query.isAdd ? '商品新增' : '详情'}
      tabActiveKey={currTabKey}
      onTabChange={onTabChange}
      tabList={operationTabList}
    >
      {contentList[tabStatus.operationKey]}
    </PageContainer>
  );
};

export default Advanced;
