import React, { useState, useEffect } from 'react'
import { Button, Table, Input, Message, Loading, Radio, Balloon } from '@alifd/next';
import { CustomMessage } from '@/components/CustomMessage'
import { urlToFile } from './utils';
import IconCom from '@/components/IconCom';
const RadioGroup = Radio.Group

export default function DesignPic() {
  const [uploadUrl, setUploadUrl] = useState<string>("");
  // 添加状态管理表格数据
  const [tableData, setTableData] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [isPage, setIsPage] = useState(true);
  const [btnLoading, setBtnLoading] = useState(false);
  const [isPreImg, setIsPreImg] = useState(-1)
  const [errImgDatas, setErrImgDatas] = useState<any[]>([])


  useEffect(() => {
    is_temu_design()
  }, [])

  const is_temu_design = async () => {
    try {
      // 获取当前活动标签页
      const [tab] = await browser.tabs.query({ active: true, currentWindow: true });

      // 获取页面域名
      if (tab.url) {
        const url = tab.url
        console.log('当前页面域名:', url);
        if (url.includes('main/customize-goods')) {
          // temu定制页面
          setIsPage(false)
        }
      }
    } catch (error) {
      console.error('获取当前页面域名时出错:', error);
    }
  }

  const order_render = (value: any, index: any, record: any) => {
    return (
      <div>{index + 1}</div>
    )
  }

  const design_render = (value: any, index: any, record: any) => {
    return <>
      {
        record.pre_info && record.pre_info.pre_pic ? <>
          <div className='flex items-center justify-center'><img className='size-20' src={record.pre_info?.pre_pic} /></div></> : <>
          <span>暂无图片</span>
        </>
      }
    </>
  }


  const pic_render = (value: any, index: any, record: any) => {
    return (
      <>
        {
          record.design_pic ? <>
            <div className='flex items-center justify-center'><img className='size-20' src={record.design_pic} /></div></> : <>
            <span>暂无图片</span>
          </>
        }
      </>
    );
  }

  const text_render = (value: any, index: any, record: any) => {
    return (
      <p>{record.text}</p>
    );
  }


  // 修改图片名称渲染函数
  const name_render = (value: any, index: number, record: any) => {
    return <>
      <div>{record.order_no}</div>
    </>
  };

  // 修改图片标签渲染函数
  const label_render = (value: any, index: number, record: any) => {
    return <>
      <div>{record.region}</div>
    </>
  };

  // 完善删除功能
  const handleDelete = (index: number, record: any) => {
    // 方案1: 直接删除
    const newData = [...tableData];
    newData.splice(index, 1);
    setTableData(newData);

    // 方案2: 带确认的删除 (可选)
    // if (window.confirm(`确定要删除 "${record.title.name}" 吗?`)) {
    //   const newData = [...tableData];
    //   newData.splice(index, 1);
    //   setTableData(newData);
    //   Message.success('删除成功');
    // }
  };

  // 删除操作渲染函数
  const option_render = (value: any, index: number, record: any) => {
    return (
      record.is_upload ? <p className='text-green-600'>上传成功</p> : <div className='flex justify-between' style={{ alignItems: 'center' }}>
        <a
          className='text-red-600 cursor-pointer'
          onClick={() => handleDelete(index, record)}
        >
          删除
        </a>
        {record.is_error && <p className='text-gray-600' style={{ marginBottom: 0 }}>上传失败</p>}
      </div>
    );
  };

  // 添加行索引以确保正确删除
  const dataSourceWithIndex = tableData.map((item, index) => ({
    ...item,
    index
  }));

  const getPicData = async () => {
    const [tab] = await browser.tabs.query({ active: true, currentWindow: true });
    // 获取页面域名
    if (tab.url) {
      const url = tab.url
      if (!url.includes('main/customize-goods')) {
        // temu定制页面
        CustomMessage.error('当前页面不是定制页面')
        return
      }
    }
    try {
      setLoading(true)
      // 获取上传路径
      fetch('http://merchant.landwu.com/api/photo/getUploadUrl', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          api_token: localStorage.getItem('access_token'),
        }),
      }).then(resjson => {
        return resjson.json();
      }).then(res => {
        if (res.data) {
          const { data = {} } = res;
          const { url = null } = data;
          setUploadUrl(url)
        }
      }).catch(e => {
        setLoading(false)
      })

      setTableData([])
      setBtnLoading(true)
      // 获取当前活动标签页
      const [tab] = await browser.tabs.query({ active: true, currentWindow: true });

      if (tab.id) {
        // 发送消息到content script请求获取tbody数据
        const response = await browser.tabs.sendMessage(tab.id, { action: "getTbodyData" });
        // 在控制台输出结果
        if (response.tables && response.tables.length > 0) {
          // console.log("找到的表格数据(包含背景图片):");
          // 显式声明类型
          let tables_arr: {
            good_info: any;
            sku_info: any;
            order_no: any;
            design_sku: any;
            pre_design_info: any;
            design_info: { region: any; text: any; picture: any }[];
          }[] = [];
          let table_boj: {
            good_info: any;
            sku_info: any;
            order_no: any;
            design_sku: any;
            pre_design_info: any;
            design_info: { region: any; text: any; picture: any }[];
          } = {
            good_info: null,
            sku_info: null,
            order_no: null,
            design_sku: null,
            pre_design_info: null,
            design_info: []
          };

          response.tables.forEach((table_node: any, index: number) => {
            console.log(`表格 ${index + 1}:`, table_node);
            // 处理成接口参数

            // 处理成数组对象
            if (table_node.length > 4) {
              if (table_boj.design_info.length) {
                // 一个商品的定制信息
                tables_arr.push(table_boj)
                // 重置
                table_boj = {
                  good_info: null,
                  sku_info: null,
                  order_no: null,
                  design_sku: null,
                  pre_design_info: null,
                  design_info: []
                }
              }
              table_boj = {
                good_info: table_node[1],
                sku_info: table_node[2],
                order_no: table_node[3],
                design_sku: table_node[4],
                pre_design_info: table_node[13],
                design_info: [{
                  region: table_node[9],
                  text: table_node[10],
                  picture: table_node[11],//11
                }]
              }
            } else {
              table_boj.design_info.push({
                region: table_node[0],
                text: table_node[1],
                picture: table_node[2],//2
              })
            }
            // 循环结束
            if (index == response.tables.length - 1) {
              if (table_boj.design_info.length) {
                // 一个商品的定制信息
                tables_arr.push(table_boj)
              }
            }
            // good_info  sku_info  design_info: region text picture 
          });

          console.log(tables_arr, "tables_arrddd")

          // 上传图片和文字的参数处理
          let pic_text_arr: any[] = [], img_values: any = {}
          tables_arr.forEach(item => {
            let order_no = "", data_params: any[] = [], pre_info = {};
            if (item.order_no && item.order_no != "-") {
              order_no = item.order_no.substring(0, 15); // 取前15位
            }
            if (order_no) {
              let pre_pic = ""
              if (item.pre_design_info && item.pre_design_info != '-') {
                let pre_pic1 = (item.pre_design_info.backgroundImages as { url: string }[] | undefined)?.[0]?.url ?? '';
                pre_pic = pre_pic1.split('&imageMogr2/thumbnail')[0]
                if (!img_values[pre_pic]) {
                  img_values[pre_pic] = {
                    src: pre_pic,
                    width: '',
                    height: '',
                    order_no,
                    file: ''
                  }
                }
                if (pre_pic) {
                  pre_info = {
                    pre_pic,
                    width: 400,
                    height: 400
                  }
                }
              } else {
                pre_pic = ""
              }
            }
            // 定制信息处理
            if (item.design_info.length) {
              item.design_info.forEach(items => {
                const param: any = {}
                if (order_no || item.design_sku) {
                  let bg_pic = ""
                  if (items.picture && items.picture != '-') {
                    let bg_pic1 = (items.picture.backgroundImages as { url: string }[] | undefined)?.[0]?.url ?? '';
                    bg_pic = bg_pic1.split('&imageMogr2/thumbnail')[0]
                    if (!img_values[bg_pic]) {
                      img_values[bg_pic] = {
                        src: bg_pic,
                        width: '',
                        height: ''
                      }
                    }
                    if (bg_pic) {
                      param['width'] = 400;
                      param['height'] = 400;
                    }
                  } else {
                    bg_pic = ""
                  }
                  let des_text = ""
                  if (items.text && items.text != '-') {
                    const des_text1 = items.text.split(";}")[1]
                    des_text = des_text1.split("查看")[0]
                  } else {
                    des_text = ""
                  }
                  param['region'] = items.region
                  param['text'] = des_text
                  param['design_pic'] = bg_pic
                  data_params.push(param)
                }
              })
            }
            if (order_no || item.design_sku) {
              pic_text_arr.push({
                order_no,
                design_sku: item.design_sku,
                pre_info,
                data_params
              })
            }
          })
          // console.log(img_values,'-img_valuesimg_values')
          let img_values1: any = {}, cIndex = 0
          Object.values(img_values).forEach((item, n) => {
            if (!img_values1[n]) {
              img_values1[n] = item
            }
          })

          const queueImg = () => {
            if (img_values1[cIndex]) {
              cIndex++
              queueImg()
              return
              {
                let img = new Image()
                img.onload = function () {
                  img_values1[cIndex].width = img.width
                  img_values1[cIndex].height = img.height
                  img_values[img_values1[cIndex]?.src]['width'] = img.width
                  img_values[img_values1[cIndex]?.src]['height'] = img.height
                  cIndex++
                  queueImg()

                }

                img.onerror = function () {
                  cIndex++
                  queueImg()
                }
                img.src = img_values1[cIndex]?.src
              }

            } else {
              getImgWh()
            }
          }
          queueImg()
          function getImgWh() {
            setBtnLoading(false)
            setLoading(false)
            // 筛选备货单号存在的值
            let pic_text_arr1 = pic_text_arr.filter(item => item.order_no && item.order_no != "-")
            // 为存在图片的对象添加宽高
            // pic_text_arr1.map(item => {
            //   item.data_params.map((items: any) => {
            //     if (items.design_pic) {
            //       if (img_values[items.design_pic]) {
            //         items['width'] = img_values[items.design_pic].width
            //         items['height'] = img_values[items.design_pic].height
            //         items['file'] = img_values[items.design_pic].file
            //       }
            //     }
            //   })
            //   if (item.pre_info && item.pre_info.pre_pic) {
            //     item.pre_info.width = img_values[item.pre_info.pre_pic].width
            //     item.pre_info.height = img_values[item.pre_info.pre_pic].height
            //   }
            // })
            // 数据显示
            let table_data: any[] = []
            pic_text_arr1.forEach(item => {
              if (item.data_params.length) {
                item.data_params.forEach((items: any) => {
                  table_data.push({
                    order_no: item.order_no,
                    pre_info: item.pre_info,
                    design_sku: item.design_sku,
                    design_pic: items.design_pic,
                    file: items.file,
                    region: items.region,
                    text: items.text,
                    width: items.width || "",
                    height: items.height || "",
                  })
                })
              }
            })
            console.log(pic_text_arr1, "pic_text_arr1aaa", img_values1)
            // console.log(table_data, "table_data")
            setTableData(table_data)
          }


        } else {
          console.log("页面上未找到表格数据");
          CustomMessage.error("页面上未找到表格数据");
        }
      }
    } catch (error) {
      setBtnLoading(false)
      setLoading(false)
      console.error("获取表格数据失败:", error);
      CustomMessage.error("获取表格数据失败");
    }
  };

  interface imgValuesProps {
    [key: string]: {
      design_pic: string,
      design_sku: string
      url: string
      width: string | number
      height: string | number
    },
  }
  const uploadPic = () => {
    try {
      const token = localStorage.getItem("access_token");
      console.log(tableData, "tableData")
      let table_obj: { [key: string]: any } = {},
        img_values: imgValuesProps = {}, fetch_url = "";
      tableData.forEach(item => {
        // 定制图
        if (item.design_pic && !img_values[item.design_pic]) {
          img_values[item.design_pic] = {
            design_pic: item.design_pic,
            design_sku: item.design_sku,
            url: '',
            width: '',
            height: ''
          }
        }
        if (isPreImg == 1) {
          // 预览图
          if (item.pre_info && item.pre_info.pre_pic && !img_values[item.pre_info.pre_pic]) {
            img_values[item.pre_info.pre_pic] = {
              design_pic: item.pre_info.pre_pic,
              design_sku: item.design_sku,
              url: '',
              width: '',
              height: ''
            }
          }
        }
        if (!table_obj[item.design_sku]) {
          table_obj[item.design_sku] = ""
        }
        if (table_obj[item.design_sku]) {
          const data_params = table_obj[item.design_sku].data_params
          data_params.push({
            design_pic: item.design_pic,
            file: item.file || "",
            region: item.region,
            text: item.text,
            width: item.width,
            height: item.height,
          })
          table_obj[item.design_sku] = {
            ...table_obj[item.design_sku],
            data_params,
          }
        } else {
          if (isPreImg == 1) {
            table_obj[item.design_sku] = {
              order_no: item.order_no,
              design_sku: item.design_sku,
              pre_info: item.pre_info,
              data_params: [{
                design_pic: item.design_pic,
                file: item.file || '',
                region: item.region,
                text: item.text,
                width: item.width,
                height: item.height,
              }]
            }
          } else {
            table_obj[item.design_sku] = {
              order_no: item.order_no,
              design_sku: item.design_sku,
              data_params: [{
                design_pic: item.design_pic,
                file: item.file || '',
                region: item.region,
                text: item.text,
                width: item.width,
                height: item.height,
              }]
            }
          }
        }
      })
      if (uploadUrl.includes('http')) {
        fetch_url = `${uploadUrl}photo/temuUploadStepTwo`
      } else {
        fetch_url = `https:${uploadUrl}photo/temuUploadStepTwo`
      }
      if (!uploadUrl) {
        CustomMessage.warning("上传地址丢失,请再次点击获取定制数据!")
        return
      }
      if (Object.values(img_values) && Object.values(img_values).length) {
        let queImgs: any = {}, queImgsCindex = 0, imgall_values: any = {};
        Object.values(img_values).forEach((v, cindex) => {
          if (!queImgs[cindex]) {
            queImgs[cindex] = {
              design_pic: v.design_pic,
              design_sku: v.design_sku,
            }
          }
        })

        const imgUpdate = () => {
          if (queImgs[queImgsCindex]) {
            setLoading(true)
            urlToFile(queImgs[queImgsCindex]?.design_pic, `${new Date().getTime()}.png`).then(file => {
              if (!file) {
                // 图片转化二进制失败
                errImgDatas.push(queImgs[queImgsCindex])
                setErrImgDatas(errImgDatas);
                queImgsCindex++
                imgUpdate()
                return
              }
              // photo/temuUploadStepTwo
              let form_data = new FormData()
              form_data.append('api_token', token as string)
              form_data.append('file', file)

              fetch(`https:${uploadUrl}photo/temuUploadStepOne`, {
                method: 'POST',
                headers: {
                  // 'Content-Type': 'multipart/form-data',
                  'access-control-allow-credentials': 'true',
                  'X-CSRF-TOKEN': 'Bearer ' + token,
                  'Authorization': 'Bearer ' + token,
                },
                body: form_data,
              }).then(resjson => {
                return resjson.json();
              }).then(res => {
                const { data } = res;
                if (!imgall_values[queImgs[queImgsCindex].design_sku]) {
                  imgall_values[queImgs[queImgsCindex].design_sku] = {
                  }
                }
                if (!imgall_values[queImgs[queImgsCindex].design_sku][queImgs[queImgsCindex].design_pic]) {
                  imgall_values[queImgs[queImgsCindex].design_sku][queImgs[queImgsCindex].design_pic] = {
                    ...data
                  }
                }
                if (imgall_values[queImgs[queImgsCindex].design_sku][queImgs[queImgsCindex].design_pic]) {
                  imgall_values[queImgs[queImgsCindex].design_sku][queImgs[queImgsCindex].design_pic] = {
                    ...data
                  }
                }
                queImgsCindex++
                imgUpdate()

              }).catch(error => {
                queImgsCindex++
                imgUpdate()
              })
            })
          } else {

            for (let key in table_obj) {
              if (imgall_values[key]) {
                // 定制图
                if (table_obj[key].data_params && Array.isArray(table_obj[key].data_params) && table_obj[key].data_params.length) {
                  const design_pic = table_obj[key].data_params.find((item: any) => item.design_pic)
                  if (design_pic) {
                    table_obj[key].data_params.map((item: any) => {
                      if (item.design_pic && imgall_values[key][item.design_pic]) {
                        const { width, height, url, type } = imgall_values[key][item.design_pic]
                        item['width'] = width
                        item['height'] = height
                        item['file'] = url
                        item['type'] = type
                        // console.log(item)
                      }
                      return item
                    })
                  }
                }
                // 预览图
                if (isPreImg == 1) {
                  if (table_obj[key].pre_info && table_obj[key].pre_info.pre_pic && imgall_values[key][table_obj[key].pre_info.pre_pic]) {
                    const { width, height, url, type } = imgall_values[key][table_obj[key].pre_info.pre_pic]
                    table_obj[key].pre_info = {
                      ...table_obj[key].pre_info,
                      width,
                      height,
                      file: url,
                      type,
                    }
                  }
                }
              }
            }
            // console.log(imgall_values, '-imgall_values', table_obj)
            imgFetchFun(table_obj)
          }
        }
        imgUpdate()
        return
      }
      function imgFetchFun(table_obj: any) {
        const table_params = Object.values(table_obj)
        let arr_index = 0
        const FetchFun = (params: any) => {
          params['api_token'] = token
          fetch(fetch_url, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify(params),
          }).then(resjson => {
            return resjson.json();
          }).then(res => {
            if (res.data.error && res.data.error.length) {
              // 未上传成功的 图片
              console.log(res.data.error, "arr_index", arr_index)
              res.data.error.forEach((item: any) => {
                CustomMessage.error(item.design_pic)
              })
            }
            // tableData循环出备货单相同的数据,修改表格操作数据 is_upload
            let tableData1 = tableData.map(item => {
              if (item.order_no == params.order_no) {
                // console.log(item.order_no, "item.order_no", params)
                item.is_upload = true
              }
              // console.log(errImgDatas, "errImgDatas")
              errImgDatas.forEach((items) => {
                // 定制图上传失败
                if (items.design_pic == item.design_pic) {
                  // 429错误
                  item.is_upload = false
                  item.is_error = true
                }
                // 预览图上传失败 概率小速度慢暂时不做处理
                // if (isPreImg == 1) {
                //   if (items.design_pic == item.pre_info.pre_pic) {
                //     item.is_upload = false
                //     item.is_error = true
                //   }
                // }
              })
              return item
            })
            setTableData(tableData1)
            arr_index++
            if (arr_index < table_params.length) {
              // console.log(tableData1,"tableData111")
              FetchFun(table_params[arr_index])
            } else {
              setLoading(false)
              setTableData(tableData.filter(item => !item.is_upload))
              setErrImgDatas([])
              CustomMessage.success("图片上传结束")
            }
          }).catch(err => {
            // console.log(err, "err")
            arr_index++
            if (arr_index < table_params.length) {
              FetchFun(table_params[arr_index])
            } else {
              setLoading(false)
              setTableData(tableData.filter(item => !item.is_upload))
              setErrImgDatas([])
              CustomMessage.success("图片上传结束")
            }
          })
        }
        setLoading(true)
        FetchFun(table_params[arr_index])
      }
      imgFetchFun(table_obj)
    } catch (error) {
      console.error(error, "报错")
    }
  }

  const evChangeRadio = (e: any) => {
    let ev = e && e.target ? e.target.value : e
    setIsPreImg(ev)
  }

  return (
    <Loading visible={loading} fullScreen>
      <div className='w-3xl h-fit'>
        <Button
          type="primary"
          disabled={isPage || btnLoading}
          style={{ marginBottom: '10px', marginRight: '10px' }}
          onClick={() => {
            getPicData()
          }}>获取定制数据</Button>
        <Button
          disabled={(!tableData.length) || isPage || btnLoading}
          type="primary"
          style={{ marginBottom: '10px', marginRight: '10px' }}
          onClick={() => {
            uploadPic()
          }}>上传定制信息</Button>
        <span className='text-red-500'>ps:需在Temu定制商品内容页面获取数据,且上传图片过程中请勿关闭插件</span>
        <div className='flex items-center' style={{ marginBottom: '10px' }}>
          <p style={{ fontSize: 14, marginBottom: 0, marginRight: 5 }}>是否获取合成预览图: </p>
          <RadioGroup value={isPreImg} onChange={(e) => {
            evChangeRadio(e)
          }} aria-labelledby="groupId">
            <Radio value={1}>
              是
            </Radio>
            <Radio value={-1}>
              否
            </Radio>
          </RadioGroup>
        </div>
        <Table dataSource={dataSourceWithIndex}>
          <Table.Column title="序号" cell={order_render} align="center" />
          <Table.Column title="备货单" cell={name_render} align="center" />
          {
            isPreImg == 1 && <Table.Column title="合成预览图" cell={design_render} align="center" />
          }
          <Table.Column title="定制区域" cell={label_render} align="center" />
          <Table.Column title="文字" cell={text_render} align="center" />
          <Table.Column title="图片" cell={pic_render} align="center" />
          <Table.Column title={<div className='flex justify-center items-center'>
            <div>操作</div><Balloon v2 closable={false} trigger={<a><IconCom type="info" _style={{cursor:'pointer', marginLeft: 5}} /></a>} align="t" triggerType="hover" style={{ width: 300 }}>
              图片上传失败时,请重新点击上传定制信息按钮
            </Balloon>
          </div>} cell={option_render} align="center" />
        </Table>
        <p className='text-red-500'>ps:若获取不到数据,可能是插件未连接成功,请刷新页面</p>
      </div>
    </Loading>
  )
}