import { Button, message, Input, Card, Select, Radio, Tag, Upload, Descriptions,Popconfirm } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { CloseOutlined, DeleteOutlined, FormOutlined } from '@ant-design/icons';
import { ProCard } from '@ant-design/pro-Card';
import { BetaSchemaForm } from '@ant-design/pro-form';
import {
  getbyidgoods,
  GetGoodsTechnology,
  GetTechnologyactionList,
  GetTechnologyActionListAll,
  GetGoodsTechnologyAction,
  DeleteGoodsTechnologyAction,
  GetByTypebatching,
  GetDeviceTechnology,
  AddGoodsTechnologyAction,
  UpdateGoodsTechnologyAction,
  deletebydevidegoodstechnologyaction
} from '../../goodsInfo/service';
import style from '../style.less'
import EditFrom from '../components/EditFrom'
import useFetchData from '@ant-design/pro-descriptions/lib/useFetchData';
const goodstechnologymaken = (props) => {
  const [attrvalue, setAttrvalue] = useState('');
  const [checkvalue, setCheckvalue] = useState([]);
  const [items, setItems] = useState([]);
  const [goodstechnologydata, setgoodstechnologydata] = useState([]);
  const [technologyattrdata, setTechnologyattrdata] = useState([]);
  const [technologyattralldata, setTechnologyattralldata] = useState([]);
  const [goodsinfo, setGoodsinfo] = useState({});
  const [cardcount, setCardcount] = useState([]);
  const [goodstechnolog, setgoodstechnolog] = useState([]);
  const [maxsort, setmaxsort] = useState(1);
  const [batchingdata, setbatchingdata] = useState([]);
  const [DeviceTechnologydata, setDeviceTechnology] = useState([])
  const [DeviceTechnologyoption, setDeviceTechnologyoption] = useState([])
  const [display, setdisplay] = useState("block")
  const [fromdata, setfromdata] = useState([])
  const [UpdataStatus, setUpdataStatus] = useState('view')
  const [disabled, setdisabled] = useState(false)
  const [devideId, setddevideId] = useState('0')
  const [defaultValue, setdefaultValue] = useState('')
  const [defaultattrValue, setdefaultattrValue] = useState('')
  const [opreaction, setopreaction] = useState('add')
  useEffect(() => {
    interdata()
  }, [])
  const interdata = () => {
    console.log("props.goodsid",props.goodsid)
    if(props.goodsid!=undefined){
      getbyidgoods(props.goodsid).then((res) => {
        if (res.succeeded) {
         
          if (res.data.goodsAttributeList.length == 0) {
            setdisplay("none")
          }else{
            res.data.goodsAttributeList.forEach(item=>{
              item.defalutvalue=[];
              item.goodsAttributeValueList.forEach(x=>{
                if(item.attributeName=="默认属性"){
                  x.check=true;
                  setAttrvalue(x.attributeValue)
                  item.defalutvalue.push(x.goodsAttributeValuId)
                }else{
                  x.check=false;
                }
              })
            })
          }
          console.log("商品属性",res.data)
          setGoodsinfo(res.data)
          var it = [
            // {key:'1',label:'',children:(<div><img style={{width:100,height:100}} src={res.data.imgUrl}></img></div>)},
            { key: '1', label: '商品名称', children: res.data.name },
            { key: '2', label: '商品价格', children: res.data.price },
            { key: '3', label: '商品类型', children: res.data.goodsTypeName },
            { key: '4', label: '商品单位', children: res.data.goodsUintName },
          ]
          setItems(it)
        } else {
          message.error("查询商品信息失败");
        }
      });
    }
    
    // GetGoodsTechnology().then((r) => {
    //   var data = r.data;
    //   var sd = []
    //   if (data.length > 0) {
    //     data.forEach((x) => {
    //       sd.push({ label: x.name, value: x.id, isBatch: x.isBatch });
    //     });
    //     setgoodstechnologydata(sd)
    //   }
    // });
    // GetTechnologyActionListAll().then((r) => {
    //   setTechnologyattralldata(r.data)
    // })
    GetGoodsTechnologyAction(props.goodsid).then((r) => {
      if (r.data.length > 0) {
        setgoodstechnolog(r.data)
        // 查询最大值
        var max = r.data.reduce(function (prev, current) {
          return (prev.sort > current.sort) ? prev : current;
        });
        console.log("最大序号：", max.sort)
        setmaxsort(max.sort)
      }
    })
    GetByTypebatching().then((r) => {
      setbatchingdata(r.data)
    })
    GetDeviceTechnology().then((res) => {
      setDeviceTechnology(res.data)
      if (res.data.length > 0) {
        var op = res.data.map(x => {
          return { value: x.id, label: x.deviceName }
        })
        setDeviceTechnologyoption(op)
      }
    })
  }
  const onChangevalue = (e) => {
    console.log(checkvalue)
   
    const { name, value } = e.target;
    let names = "";
    let updatedValues = [...checkvalue];
    for (let index = 0; index < goodsinfo.goodsAttributeList.length; index++) {
      if (name === 'radiogroup' + index) {
        // 将第一组的值累加到数组中  
        updatedValues[index] = value;

      }
    }
    goodsinfo.goodsAttributeList.forEach(item => {
      for (let index = 0; index < updatedValues.length; index++) {
        var bs = item.goodsAttributeValueList.find(x => x.goodsAttributeValuId == updatedValues[index])?.attributeValue
        if (bs) {
          names = names + bs;
          if (index < updatedValues.length - 1) {
            names = names + "-"
          }
        }

      }
      item.goodsAttributeValueList.forEach(x=>{
        if(value==x.goodsAttributeValuId){
          x.check=true;
        }
      })
    })
    setAttrvalue(names)
    setCheckvalue(updatedValues)
  }
  const onClickedit = (e, item, action) => {
    setopreaction("update")
    if (UpdataStatus != "add") {
      setdefaultValue(item.deviceId)
      //handleChange(item.deviceId)
      setdefaultValue(item.deviceId)
      setddevideId(item.deviceId)
      GetGoodsTechnologyvalue(item.deviceId,"edit",item)
     
      //console.log("attr", attr)
     
      setUpdataStatus("update")
    } else {
      message.error("请保存当前数据后在编辑");
    }

    //setTechnologyattrdata(attr)
  }
  const editfrom=(item,Technologyacton)=>{
    let attr = [];
    item.data.forEach(item => {
      const obj = {};
      let propsdatanew = [];
      let propsdata = Technologyacton?.filter(x => x.technologyId == item.chnologyId)
      obj.stepName = item.stepName;
      obj.id = item.id;
      obj.chnologyId = item.chnologyId;
      obj.sort = item.sort;
      obj.actionJson = item.actionJson
      obj.optiondata = JSON.parse(item.actionJson)
      propsdata?.forEach(x => {
        let sd = {
          id: x.id,
          actionName: x.actionName,
          actionType: x.actionType,
          actionValue: x.actionValue,
          goodstechnologyId: x.technologyId,
          isBatch: x.isBatch,
          sort: x.sort,
          goddteid: item.id
        }
        propsdatanew.push(sd)
      })
      obj.propsdata = propsdatanew;
      obj.isBatch = item.isBatch;
      obj.typeName = item.stepName;

      attr.push(obj)
    })
    setfromdata(attr)
  }
  const GetGoodsTechnologyvalue=(value,va,item)=>{
    let godata=[]
    console.log("va",va)
    GetGoodsTechnology(value).then((r)=>{
      if (r.data.length > 0) {
        var Technologyacton=[];
        godata = r.data?.map(x => {
          
          if(x.technologyActionInfo.length>0){
            x.technologyActionInfo.forEach(p=>{
              Technologyacton.push(p);
            })
          }
          return { value: x.id, label: x.name }
        })
        console.log("godata",godata)
        setTechnologyattralldata(Technologyacton)
        setgoodstechnologydata(godata)
      }else{
        setTechnologyattralldata([])
        setgoodstechnologydata([])
      }
      //setfromdata([])
      if(va=="edit"){
        editfrom(item,Technologyacton)
      }
    })
    
  }
  //删除单个工艺
  const onClickdele = (e, item, action) => {
    DeleteGoodsTechnologyAction(item.id).then((res) => {
      if (res.data) {
        message.success("删除成功")
        console.log(fromdata)
        //formRef?.current?.resetFields(...props.technologyattrdata)
        updadata()
      } else {
        message.error("删除失败")
      }
    })
  }
  //删除设备工艺
  const onClickDevicedele = (e, devideId, action) => {
    deletebydevidegoodstechnologyaction({ devideId: devideId, goodsId: props.goodsid }).then((res) => {
      if (res.data) {
        message.success("删除成功")
        setgoodstechnolog([])
        //formRef?.current?.resetFields(...props.technologyattrdata)
        updadata()
      } else {
        message.error("删除失败")
      }
    })
  }
  //更新查工艺列表
  const updadata = () => {
    GetGoodsTechnologyAction(props.goodsid).then((r) => {
        if (r.data.length > 0) {
          setgoodstechnolog(r.data)
          // 查询最大值
          var max = r.data.reduce(function (prev, current) {
            return (prev.sort > current.sort) ? prev : current;
          });
          setmaxsort(max.sort);
          let attr = { attributes: [] };
          setTechnologyattrdata(attr)
        }else{
          setTechnologyattrdata([])
          setgoodstechnolog([])
        }
    })
  }
  const handleChange = (value) => {
    console.log("进来了", value)
    setdefaultValue(value)
    setddevideId(value)
    GetGoodsTechnologyvalue(value,"",null)
    // let sd = DeviceTechnologydata.find(x => x.id == value);
    // if (sd) {
    //   if (sd.goodsTechnologyInfo.length > 0) {
    //     godata = sd.goodsTechnologyInfo.map(x => {
    //       return { value: x.deviceTechnologyId, label: x.name }
    //     })
       
    //     setgoodstechnologydata(godata)
    //   }
    //   setfromdata([])
    // }
    // console.log("godata", godata)
    // setgoodstechnologydata(godata)
  }
  const onUpdataStatus = (val) => {
    setUpdataStatus(val)
  }
  const onSaveClick = (val) => {
    console.log("222",val)
    setfromdata(val)
  }
  const onSubmitSaveClick = () => {
    console.log("保存的数据", fromdata)
    let check = true;
    var data = []
    fromdata.forEach(x => {
      let item = {};
      item.deviceId = devideId
      item.id = x.id
      item.stepName = x.stepName;
      item.chnologyId = x.chnologyId;
      item.isBatch = x.isBatch;
      if (UpdataStatus != "add") {
        item.sort = x.sort;
      }
      if (x.optiondata.length == 0) {
        check = false;
      } else {
        item.actionJson = JSON.stringify(x.optiondata);
      }
        x.optiondata.forEach(f=>{
          var df=x.propsdata.find(x=>x.id==f.technologyactionId)
          if(df){
            if(df.actionType=="select" && f.actionValue==''){
              check = false;
            }
            if(df.actionType=="digit" && (f.actionValue==='' || f.actionValue===null)){
              check = false;
            }
          }else{
            if(f.actionValue===''){
              check = false;
            }
          }
          
        })
      
     
      // var vacheck=x.optiondata.find(x=>x.actionValue=='')
      // if(vacheck){
      //   check = false;
      // }
      item.goodsId = props.goodsid
      item.goodsAttributeId = checkvalue.join(',')
      if (x.chnologyId == "") {
        check = false;
      }
      data.push(item)
    })
    console.log("转化后要保存的数据", data)
    console.log("更新添加状态", UpdataStatus)
    if (data.length > 0 && check) {
      if (UpdataStatus == "add") {
        AddGoodsTechnologyAction(data).then((res) => {
          if (res.data) {
            message.success("保存成功")
            setfromdata([])
            updadata()
          } else {
            message.error("保存失败")
          }
        })

      } else {
        UpdateGoodsTechnologyAction(data).then((res) => {
          if (res.data) {
            message.success("保存成功")
            setfromdata([])
            updadata()
          } else {
            message.error("保存失败")
          }
        })

      }
      setUpdataStatus("view")
      setdisabled(false)
      setopreaction("add")
    } else {
      message.error("没有要保存的数据或数据格式不正确")
    }
 
  }
  const cancel = (e) => {
    console.log(e);
    message.error('取消删除');
  };
  return <>

    <Card bodyStyle={{ padding: 15 }}>
      <div style={{ fontSize: 16, marginBottom: 5, color: '#1890ff', fontWeight: 600 }}>商品信息</div>
      <div style={{ float: 'left' }}><img style={{ width: 100, height: 100 }} src={goodsinfo.imgUrl}></img></div>
      <Descriptions style={{ float: 'left', width: '71%', marginLeft: '10px' }} labelStyle={{ fontSize: 16, fontWeight: 600 }} >

        {
          items.map((x, index) => {
            return (
              <Descriptions.Item key={index} label={x.label}>{x.children}</Descriptions.Item>
            );
          })
        }

      </Descriptions>
    </Card>
    <Card bodyStyle={{ padding: 15 }} style={{ display: display }} >
      <div style={{ fontSize: 16, marginBottom: 5, color: '#1890ff', fontWeight: 600 }}>商品属性</div>
      {
        goodsinfo.goodsAttributeList == undefined ? '' : (
          goodsinfo.goodsAttributeList.map((item, index) => {
            return (
              <div style={{ marginLeft: 10 }}>
                <div>
                  <span style={{ marginRight: 10 }}> <Tag color="blue" style={{ fontSize: 14, fontWeight: 600 }}>{item.attributeName}</Tag>：</span>
                  <span>
                    <Radio.Group name={"radiogroup" + index} buttonStyle="solid" onChange={onChangevalue} defaultValue={item.defalutvalue}>
                      {
                        item.goodsAttributeValueList.map((x, index) => {
                          return (
                            <Radio.Button key={index} name={index} defaultChecked={x.check} value={x.goodsAttributeValuId} style={{ marginRight: 22, marginTop: 10 }}>{x.attributeValue}</Radio.Button>
                          )
                        })
                      }
                    </Radio.Group>
                  </span>
                </div>
              </div>
            );
          })
        )
      }
    </Card>
    <Card bodyStyle={{ padding: 15 }} >
      <div style={{ fontSize: 16, marginBottom: 5, color: '#1890ff', fontWeight: 600 }}>选择设备：
      <Select
              showSearch
              allowClear
              style={{
                width: 200,
                marginRight: 10
              }}
              value={defaultValue}
              placeholder="请选择设备"
              optionFilterProp="children"
              filterOption={(input, option) => (option?.label ?? '').includes(input)}
              filterSort={(optionA, optionB) =>
                (optionA?.label ?? '').toLowerCase().localeCompare((optionB?.label ?? '').toLowerCase())
              }
              onChange={handleChange}
              options={DeviceTechnologyoption}
            />
      </div>
      
    </Card>
    <Card bodyStyle={{ padding: 15 }}>
      <div style={{ fontSize: 16, marginBottom: 5, color: '#1890ff', fontWeight: 600 }}>工艺设计</div>
      <ProCard split="vertical">
        <ProCard title="编辑工艺" type='inner' colSpan="33%" bodyStyle={{ padding: 5 }} headerBordered headStyle={{ paddingLeft: '5%' }} extra={
          [
         
            <Button type="primary" ghost onClick={() => { onSubmitSaveClick() }}>保存工艺</Button>
          ]
        }>
          <div style={{ textAlign: 'center', marginBottom: 10, color: 'brown' }}>{attrvalue}</div>
          <EditFrom devideId={devideId} disabled={disabled} fromdata={fromdata} maxsort={maxsort} UpdataStatus={UpdataStatus} onUpdataStatus={onUpdataStatus} onSaveClick={onSaveClick} goodstechnologydata={goodstechnologydata} technologyattralldata={technologyattralldata} batchingdata={batchingdata} />
        </ProCard>
        <ProCard title="查看工艺" type='inner' headStyle={{ paddingLeft: '45%' }} bodyStyle={{ padding: 5,width: '1072px','overflow-x': 'scroll' }} headerBordered>
          <div style={{width: 'max-content'}}>
            {
              goodstechnolog == undefined ? '' : (
                goodstechnolog.map((x, index) => {
                  return (
                    <ProCard wrap gutter={16} boxShadow title={x.deviceName+'【'+attrvalue+'】'} bodyStyle={{ padding: 0,'overflow-x': 'scrol'}} headStyle={{ padding: '0px 0px', backgroundColor: 'burlywood', paddingLeft: '40%', height: 45 }} extra={[
                      <FormOutlined style={{ marginRight: 10 }} onClick={(e) => { onClickedit(e, x) }} />,
                      // <DeleteOutlined style={{ marginRight: 6 }} onClick={(e) => { onClickDevicedele(e, x.deviceId) }} />,
                      <Popconfirm
                      title="确认删除吗?"
                      description="确认删除吗"
                      onConfirm={(e) => { onClickDevicedele(e, x.deviceId) }}
                      onCancel={cancel}
                      okText="确定"
                      cancelText="取消"
                    >
                      <DeleteOutlined style={{ marginRight: 6 }} />
                    </Popconfirm>
                    ]} style={{marginBlockEnd: 8, width: 453, float: 'left', marginRight: '10px'}}>
                      {
                        x.data.map(item => {
                          var action = JSON.parse(item.actionJson)
                          return (
                            <ProCard type="inner" hoverable layout="center" title={"工序号" + item.sort} bordered bodyStyle={{ padding: 5 }} headStyle={{ padding: '0px 5px',border:'none',backgroundColor: '#e8f0fd' }} 
                            extra={[
                              <Popconfirm
                              title="确认删除吗?"
                              description="确认删除吗"
                              onConfirm={(e) => { onClickdele(e, item, action) }}
                              onCancel={cancel}
                              okText="确定"
                              cancelText="取消"
                            >
                              <DeleteOutlined/>
                            </Popconfirm>,
                            // <DeleteOutlined onClick={(e) => { onClickdele(e, item, action) }} />
                            ]} style={{boxShadow: '5px 8px 24px 5px rgba(208, 216, 243, 0.6)'}}>
                              <div style={{ lineHeight: '200px', height: '100%', width: '100%' }}>
                                <div className={style['formlable']} style={{ float: 'left', width: '29%',backgroundColor: '#4eaaf5',color:'white' }}>{item.stepName}</div>
                                <div style={{ float: 'left', marginBottom: '5px', width: '67%', }}>
                                  {
                                    action.map(x => {
                                      return (
                                        <div style={{ float: 'left', marginBottom: '5px' }}>
                                          <div className={style['formlable']} style={{ display: 'block', float: 'left', backgroundColor: '#dcf4ff' }}>{x.actionName}</div>
                                          <div className={style['formlabletxt']} style={{ display: 'block', float: 'left' }}> {x.actionValue}</div>
                                        </div>
                                      )

                                    })
                                  }
                                </div>
                              </div>
                            </ProCard>
                          )
                        })
                      }
                    </ProCard>
                  )
                })
              )
            }
          </div>
        </ProCard>
      </ProCard>
    
    </Card>
  
  </>

}
export default goodstechnologymaken;