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 ProTable from '@ant-design/pro-table';
import CreateBom from './components/CreateBom';
// import UpdateBom from './components/UpdateBom'
// import BomBatching from './components/BomBatching'
import { addGoods} from '../newgoods/service';
import { GetGoodsBom, DelGoodsBom,getbygoodsidattribute,addgoodsbomattribute,GetbomTypelist,getproductpage,getbomlist } 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();

  useEffect(() => {
    // if(!props.location?.query?.values){
    //   history.push({
    //     pathname: '/database/goods/newgoods',
    //   });
    // }else{

      initGetbomType();
      intBatching();//默认原料
    //}
   
  }, [])
  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 bomcolumns =
    [
      {
        title: '主键',
        dataIndex: 'id',
        key: 'id',
        hideInTable: true,
        hideInSearch: true,
        tip: '规则名称是唯一的 key',
      },
      {
        title: '配方名称',
        key: 'name',
        dataIndex: 'name',
        valueType: 'textarea',
      },
      {
        title: '商品属性',
        key: 'goodsAttributeValue',
        dataIndex: 'goodsAttributeValue',
        valueType: 'textarea',
        fieldProps:{
          placeholder:'请输入属性,属性格式为：xx-xx'
        }
      },
      // {
      //   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 () => {
              try {
                DelGoodsBom(record.id).then((r)=>{
                  if(r.data){
                    message.success('删除成功，即将刷新');
                    actionRef.current.reload();
                  }else{
                    message.error('删除失败，请重试');
                    actionRef.current.reload();
                  }
                });
                return true;
              } catch (error) {
                return false;
              }
          }}
          onCancel={() => {}}
        >
          <a href="#">删除</a>
        </Popconfirm>,
        ],
      }
    ]

  return (
    <PageContainer
    host header={{
      title: [<a  key="back"
      onClick={() => {
        history.push({
          pathname: '/database/goods/newgoods',
        });
      }}><ArrowLeftOutlined />返回</a>],
      breadcrumb: {},
    }}
    >
      
      <ProTable
          columns={bomcolumns}
          actionRef={actionRef}
          rowKey="id"
          search
          toolBarRender={() => [
                 <Button
                 type="primary"
                 key="primary"
                 onClick={ async() => {
                   if (props.location.query.values?.id == undefined || props.location.query.values?.id == null) {
                     message.info('请先添加商品基础信息!');
                   } else {
                    await getbygoodsidattribute(props.location.query.values.id).then((r)=>{
                      setGoodsAttriburteData(r.data);
                    })
                    setHandleCreateoodsBomModalVisible(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);
              if(msg.data.data.length>0){
                var nom=msg.data.data.map(x=>{
                  return x.bomId;
                })
                setBomIds(nom)
              }
              getbomlist().then((r)=>{
                console.log("nom",nom)
                // if(nom.length>0){
                //   var da=[]
                //   r.data.map(x=>{
                //     var dif=nom.find(p=>p==x.id);
                //     if(!dif){
                //       da.push(x)
                //     }
                //   })
                // }
                // console.log("da",da)
                setBomdata(r.data)
              })
              return {
                data: msg.data.data,
                success: true,
                total: total,
              };
            }

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

        />
        <CreateBom handleCreateoodsBomModalVisible={handleCreateoodsBomModalVisible}  
          bomTypeData={bomTypeData}
          Bomdata={Bomdata}
        initTypeList={initTypeList}
        onFinish={async (value) => {
          value.goodsId=props.location.query.values.id;
          console.log(value)
          await addgoodsbomattribute(value).then((r)=>{
            console.log(r)
            if(r.data){
              message.success("添加成功")
              setHandleCreateoodsBomModalVisible(false);
            }else{
              message.error(r.errors)
            }
            actionRef.current.reload();
          })
        }}
        goodsid={props.location.query.values?.id}
        goodsname={props.location.query.values?.name}
        goodsAttriburteData={goodsAttriburteData}
        matedata={matedata}
        bomtype={bomtype}
        defaultmatedata={props.location.query.values?.defaultMate}
        onCancel={() => {
          setHandleCreateoodsBomModalVisible(false);
        }}
        />
    </PageContainer>
  );
};

export default Advanced;
