import React, {useEffect, useImperativeHandle, useRef, useState} from "react";
import './ProductData.less'
import closeIcon from "@/assets/brand/closeIcon.png";
import type {ProColumns} from "@ant-design/pro-table";
import ProTable from "@ant-design/pro-table";
import {handleGetAddShopList, handleGetShopTypeTree} from "@/pages/DataVerification/list/service";
import {Button, Input, Select, TreeSelect} from "antd";

const ProductData: React.FC<{ currentUser?: any, currentDetail?: any,productsDrawer: boolean,onRef: any }> = ({ currentUser,currentDetail,productsDrawer,onRef }) => {
  const tableRef = useRef()
  const [tableData,setTableData] = useState<any>()
  // 商品状态
  const [shopState,setShopState] = useState<number>(1)
  // 树列表
  const [treeData,setTreeData] = useState<any>()
  // 商品类型
  const [selectShopType,setSelectShopType] = useState<any>()
  // 搜索框内输入的内容
  const [searchText,setSearchText] = useState<string>()
  // 表格的加载效果
  const [tableLoading,setTableLoading] = useState<boolean>(false)
  // 已经选择要保存的商品
  const [selectShopList,setSelectShopList] = useState<any>()
  const columns: ProColumns<any>[] = [
    {
      dataIndex: 'COMMODITY_TYPE',
      title: '商品类型',
      valueType:'treeSelect',
      request: async () => {
        return await handleGetShopTypeTree({PROVINCE_CODE:currentUser?.ProvinceCode})
      },
    },
    {
      dataIndex: 'COMMODITY_NAME',
      title: '商品名称',
      hideInSearch: true,
    },
    {
      dataIndex: 'COMMODITY_BARCODE',
      title: '商品条码',
      hideInSearch: true,
    },
    {
      dataIndex: 'COMMODITY_CODE',
      title: '商品编码',
      hideInSearch: true,
    },
    {
      dataIndex: 'COMMODITY_UNIT',
      title: '商品单位',
      hideInSearch: true,
    },
    {
      dataIndex: 'COMMODITY_RULE',
      title: '商品规格',
      hideInSearch: true,
    },
    {
      dataIndex: 'COMMODITY_STATES',
      title: '商品状态',
      hideInTable: true,
    },
    {
      dataIndex: 'Total_Count',
      title: '销售数量',
      hideInSearch: true,
      render:(_,record)=>{
        return <Input style={{width:'70px'}} value={record.Total_Count} onInput={(e: any)=>{
          record.Total_Count = e.target.value
          const tableList = JSON.parse(JSON.stringify(tableData))
          if (record.Total_Count && record.COMMODITY_RETAILPRICE){
            record.Total_SellAmount = (Number(record.Total_Count) * Number(record.COMMODITY_RETAILPRICE)).toFixed(2)
          }
          tableList[record.key-1] = record
          console.log('record',record)
          setTableData(tableList)
          if (selectShopList && selectShopList.length>0){
            const list: any = JSON.parse(JSON.stringify(selectShopList))
            const newList: any = []
            list.forEach((item: any)=>{
              if (item.COMMODITY_CODE===record.COMMODITY_CODE){
                newList.push(record)
              }else{
                newList.push(item)
              }
            })
            setSelectShopList(newList)
          }
        }}/>
      }
    },
    {
      dataIndex: 'COMMODITY_RETAILPRICE',
      title: '销售单价',
      hideInSearch: true,
      render:(_: any,record: any)=>{
        return <Input style={{width:'70px'}} value={record.COMMODITY_RETAILPRICE} onInput={(e: any)=>{
          record.COMMODITY_RETAILPRICE = e.target.value
          const tableList = JSON.parse(JSON.stringify(tableData))
          if (record.Total_Count && record.COMMODITY_RETAILPRICE){
            record.Total_SellAmount = (Number(record.Total_Count) * Number(record.COMMODITY_RETAILPRICE)).toFixed(2)
          }
          tableList[record.key-1] = record
          setTableData(tableList)
          if (selectShopList && selectShopList.length>0){
            const list: any = JSON.parse(JSON.stringify(selectShopList))
            const newList: any = []
            list.forEach((item: any)=>{
              if (item.COMMODITY_CODE===record.COMMODITY_CODE){
                newList.push(record)
              }else{
                newList.push(item)
              }
            })
            setSelectShopList(newList)
          }
        }}/>
      }
    },
    {
      dataIndex: 'Total_SellAmount',
      title: '销售金额',
      hideInSearch: true,
      render:(_: any,record: any)=>{
        return <Input style={{width:'100px'}} value={record.Total_SellAmount} onInput={(e: any)=>{
          record.Total_SellAmount = e.target.value
          const tableList = JSON.parse(JSON.stringify(tableData))
          tableList[record.key-1] = record
          setTableData(tableList)
          if (selectShopList && selectShopList.length>0){
            const list: any = JSON.parse(JSON.stringify(selectShopList))
            const newList: any = []
            list.forEach((item: any)=>{
              if (item.COMMODITY_CODE===record.COMMODITY_CODE){
                newList.push(record)
              }else{
                newList.push(item)
              }
            })
            setSelectShopList(newList)
          }
        }}/>
      }
    },
  ]
  // 拿到表格数据的方法
  const handleGetTableData = async ()=>{
    setTableLoading(true)
    const req = {
      SearchType:-1,
      ProvinceCode:currentUser?.ProvinceCode,
      ServerpartShopID:currentDetail?.ServerpartShop_Id,
      CommodityState:shopState,
      CommodityTypeId:selectShopType,
      SearchKey:'COMMODITY_NAME',
      SearchValue:searchText,
      PageIndex:1,
      PageSize: 999999,
    }
    const data = await handleGetAddShopList(req)
    const list: any =[]
    if (data && data.List && data.List.length>0){
      data.List.forEach((item: any,index: number)=>{
        item.key=index+1
        list.push(item)
      })
    }
    console.log('list',list)
    setTableData(list)
    setTableLoading(false)
  }

  useEffect(async () => {
    if (productsDrawer){
      const options = await handleGetShopTypeTree({PROVINCE_CODE:currentUser?.ProvinceCode})
      console.log('options',options)
      setTreeData(options)
      handleGetTableData()
    }
  }, [productsDrawer]);
  useImperativeHandle(onRef, () => ({
    selectShopList
  }));

  const rowSelection: any = {
    onChange: (selectedRowKeys: any, selectedRows: any) => {
      console.log('selectedRowKeys',selectedRowKeys)
      console.log('selectedRows',selectedRows)
      setSelectShopList(selectedRows)
    },
  };

  return (
    <div className={'productData'}>
      <div className={'detailTop'}>
        <div style={{display:'flex',alignItems:'center'}}>
          <p className={'detailTitle'}>添加单品数据</p>
        </div>
        <img className={'closeIcon'} src={closeIcon}/>
      </div>

      <div className={'searchBox'}>
        <div className={'searchLeft'}>
          <div className={'searchItem'}>
            <span className={'searchLabel'}>商品类别:</span>
            <TreeSelect
              showSearch
              style={{width:'200px'}}
              allowClear
              treeData={treeData}
              onChange={(e: any)=>{
                console.log('e',e)
                setSelectShopType(e)
              }}
            />
          </div>
          <div className={'searchItem'}>
            <span className={'searchLabel'}>商品状态:</span>
            <Select
              style={{width:'200px'}}
              onChange={(e: any)=>{
                setShopState(e)
              }}
              value={shopState}
              options={[{label:'有效',value:1},{label:'无效',value:0}]}
            />
          </div>
          <Input value={searchText} style={{width:'200px'}} onInput={(e: any)=>{
            setSearchText(e.target.value)
          }}/>
        </div>
        <div className={'searchRight'}>
          <Button style={{marginRight:'8px'}} onClick={()=>{
            setSearchText('')
            setSelectShopType(null)
            setShopState(1)
            handleGetTableData()
          }}>重置</Button>
          <Button type={'primary'} onClick={()=>{
            handleGetTableData()
          }}>查询</Button>
        </div>
      </div>
      <div className={'detailContent'}>
        <ProTable
          loading={tableLoading}
          key={'key'}
          actionRef={tableRef}
          options={false}
          search={false}
          columns={columns}
          rowSelection={{
            type: 'checkbox',
            ...rowSelection,
          }}
          dataSource={tableData}
          pagination={{ pageSize: 10 }}
        >

        </ProTable>
      </div>
    </div>
  )
}

export default ProductData
