import { PlusOutlined, UploadOutlined,ArrowLeftOutlined } from '@ant-design/icons';
import { Button, Card, message, Steps, Empty, Form, Input, Upload, Select, InputNumber, Switch,TreeSelect,Divider,Space,Popconfirm } 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 CreateBom from './components/CreateBom';
// import GoodsTechnologyMaken from '../goodstechnology/components/goodstechnologymaken'
import UpdateBom from './components/UpdateBom'
import BomBatching from './components/BomBatching'
import { addGoods} from '../newgoods/service';
import { GetGoodsBom, UpdateBomInfo, DelGoodsBom, GetCosRequestURL,gettree, unitList,getbygoodsidattribute,addgoodsbomattribute,GetbomTypelist,getproductpage,addunit,getbomlist,addgoodsbom,UpdateBomBatcing } from './service'
import axios from 'axios';
import { history } from 'umi';
const { Step } = Steps;
const { Option, OptGroup } = Select;
const { TextArea } = Input;
const Advanced = (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 [handleCreateoodsBomModalVisible,setHandleCreateoodsBomModalVisible] = useState(false);
  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 [goodsAttriburteData, setGoodsAttriburteData] = useState([]);
  const [bomtype, setBomtype] = useState([]);
  const [matedata, setMatedata] = useState([]);
  const [treeData, setTreeData] = useState();
  const [unitname, setunitname] = useState('');
  const [bomTypeData,setbomTypeData]= useState([]);
  const inputRef = useRef(null);
  const [Bomdata, setBomdata] = useState([]);
  const [BomIds, setBomIds] = useState([]);
  const [BomId, setBomId] = useState();
  const [UpdateBomVisible, setUpdateBomVisible] = useState(false);
  const [BomBatchingVisible,setBomBatchingVisible]= useState(false);
  const [goodsTypeIdvalue, setgoodsTypeIdvalue] = useState();
  //事件
  const onFinish = async (values) => {
    const hide = message.loading('正在执行');
    console.log(values)
    try {
      if(props.location.query.isAdd)values.id=null;
      values.imgUrl = url ? url : values.imgUrl;
      if(values.defaultMate){
        values.defaultMate=values.defaultMate.join();
      }else{
        values.defaultMate="";
      }
      
      await addGoods(JSON.stringify(values)).then((r) => {
        if (r.succeeded) {
          message.success('操作成功');
          history.push({
            pathname: '/database/goods/newgoods',
          });
        } else {
          message.error(r.errors);
        }
      });
      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(() => {
    // if(!props.location?.query?.values){
    //   history.push({
    //     pathname: '/database/goods/newgoods',
    //   });
    // }else{
      SetCurrTabKey(tabStatus.tabActiveKey);
      initGoodsUnit();
      initGoodsType();
      initGetbomType();
      intBatching();//默认原料
    //}
   
  }, [tabStatus])
  const onTabChange = (key) => {
    if (currentGoodsProp === 1) {
      message.info('套餐不能设置配方');
      return;
    }
    seTabStatus({ operationKey: key, tabActiveKey: key });
    
    //initGoodsType()
  };
  function initGoodsUnit() {
    unitList().then((r) => {
      var list = [];
     
        if (r.data.length > 0) {
          r.data.forEach((item) => {
            list.push({text: item.name, value: item.id, label: item.name });
          });
        }
        console.log("list",list)
        setGoodsUnit(list);
      
    });
  }
  function initGoodsType() {
    gettree().then((r) => {
      setTreeData(r.data);
    });
  }
  function initGetbomType(){
    GetbomTypelist().then((r)=>{
      var list = [];
      if (r.data.length > 0) {
        r.data.forEach((item) => {
          list.push({ text: item.name, value: item.id, label: item.name });
        });
      }
      setbomTypeData(list)
    })
   
  }
  function intBatching(){
    getproductpage().then((r) => {
      setMatedata(r.data);
    });
  }
  function initTypeList(){
    initGetbomType();
  }
  const onNameChange = (event) => {
    setunitname(event.target.value);
  };
  const addItem = (e) => {
    e.preventDefault();
   
    if(unitname.length==0){
      message.error("请输入名称");
    }else{
      var parm={name:unitname}
      addunit(parm).then((r)=>{
        if(r.succeeded){
          message.success('添加成功');
          initGoodsUnit();
          setunitname('');
        }else{
          message.error(r.errors);
        }
      })
    }
  };
  const operationTabList = [
    {
      key: 'basis',
      tab: '商品基础信息',
    },
    // {
    //   key: 'goodsbom',
    //   tab: '商品配方',
    // },
    // {
    //   key: 'goodstechnologymaken',
    //   tab: '商品工艺',
    // },
  ];
  const onUpdateBomCancel=()=>{
    setUpdateBomVisible(false);
    setBomId('')
  }
  const onBomBatchingCancel=()=>{
    setBomBatchingVisible(false);
    setBomId('')
  }
  const onUpdateBomSave=(form)=>{
    form
    .validateFields()
    .then((values) => {
      console.log(values)
      var parm={id:BomId,name:values.bomName,IsMain:values.bomType=='1'?true:false,bomTypeIds:values.bomTypeList}
      UpdateBomInfo(parm).then((r)=>{
        if(r.succeeded){
          message.success('修改成功');
          setUpdateBomVisible(false);
          actionRef.current.reload();
          setBomId('')
        }else{
          message.error(r.errors);
        }
      })
    })
  }
  const onBomBatchingFinish=(form)=>{
    console.log("form",form)
    var parm={bomId:BomId,bomEntry:form};
    UpdateBomBatcing(parm).then((r)=>{
      if(r.succeeded){
        message.success('修改成功');
        setBomBatchingVisible(false);
        actionRef.current.reload();
        setBomId('')
      }else{
        message.error(r.errors);
      }
    })
  }
  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={() => {
              setUpdateBomVisible(true);
              setBomId(record.bomId)
            }}
          >
            更新
          </a>,
          <a
          key="primary"
          type="primary"
          onClick={() => {
            setBomBatchingVisible(true);
            setBomId(record.bomId)
          }}
        >
          配方详情
        </a>,
          <Popconfirm
          type="primary"
          key="primary"
          title="确认删除吗？"
          okText="是"
          cancelText="否"
          onConfirm={async () => {
            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;
              }
          }}
          onCancel={() => {}}
        >
          <a href="#">删除</a>
        </Popconfirm>,
        ],
      }
    ]
    const onChange = (newValue) => {
      setgoodsTypeIdvalue(newValue);
    };
    const filterOption = (input, option) =>
  (option?.label ?? '').toLowerCase().includes(input.toLowerCase());
  const contentList = {
    basis: (
      <Card
        title="商品基础信息"
        style={{
          marginBottom: 24,
        }}
        bordered={false}
      >
        <Form
          form={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="goodsTypeId" label="商品分类" rules={[{ required: true }]}>
          <TreeSelect
            allowClear
            showSearch
            style={{ width: '100%' }}
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            treeData={treeData}
            onChange={onChange}
            filterOption={filterOption}
            value={goodsTypeIdvalue}
            placeholder="请选择商品类型"
            treeDefaultExpandAll
          />
        </Form.Item>
          <Form.Item name="name" label="商品名称" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item name="goodsUintId" label="商品单位" rules={[{ required: true }]}>
            <Select
              style={{width: 400}}
              placeholder="请选择单位"
              showSearch
              allowClear
              filterOption={filterOption}
              options={goodsUnit}
              dropdownRender={(menu) => (
                <>
                {menu}
                <Divider style={{margin: '8px 0'}}/>
                <Space style={{padding: '0 8px 4px'}}>
                  <Input
                    placeholder="请输入单位"
                    ref={inputRef}
                    value={unitname}
                    onChange={onNameChange}
                    onKeyDown={(e) => e.stopPropagation()}
                  />
                  <Button type="text" icon={<PlusOutlined />} onClick={addItem}>
                    新增
                  </Button>
                </Space>
                </>
              )}
            />
          </Form.Item>
          <Form.Item name="price" label="商品价格" rules={[{ required: true }]}>
            <InputNumber   style={{ width: '100%' }} placeholder="价格" min={0} />
          </Form.Item>
         
          <Form.Item label="是否称重" name="isWeigh" valuePropName="checked" >
            <Switch checkedChildren="是" unCheckedChildren="否" defaultChecked={false} />
          </Form.Item>
          <Form.Item label="是否多属性" name="isAttrubute" valuePropName="checked">
            <Switch checkedChildren="是" unCheckedChildren="否" defaultChecked={false} />
          </Form.Item>
          <Form.Item name="descritption" label="备注">
          <TextArea  rows={4} />
          </Form.Item>
          {/* <Form.Item name="design" label="规格" >
            <TextArea  rows={4} />
          </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>
            <Button type="primary" htmlType="submit">
              保存
            </Button>
          </Form.Item>
        </Form>
      </Card>
    ),
  };
  return (
    <PageContainer
    host header={{
      title: [<a  key="back"
      onClick={() => {
        history.push({
          pathname: '/database/goods/newgoods',
        });
      }}><ArrowLeftOutlined />返回</a>],
      breadcrumb: {},
    }}
      title={props.location.query.isAdd ? '商品新增' : '详情'}
      tabActiveKey={currTabKey}
      onTabChange={onTabChange}
      tabList={operationTabList}
    >
      
      {contentList[tabStatus.operationKey]}
    </PageContainer>
  );
};

export default Advanced;
