// import React from 'react'
import './product-release.css'
import {
  // Select, DatePicker, Button,
  // message,
  // Checkbox, 
  Empty,
  // Switch,
  Modal, Pagination, Image,
  Spin,
  Button
} from 'antd';
import { DeleteOutlined } from '@ant-design/icons';
import { getGoodsList, submitAudit, putOnShelf, putOffShelf, deleteGoods, getSoftTypeList } from '../../request/api'
import { showImage } from '../../request/request'
import EditModal from './components/EditModal/EditModal'
import useMessage from "antd/es/message/useMessage";
// import type { CheckboxProps } from 'antd';
// import {
//   // SearchOutlined,
//   ClearOutlined
// } from '@ant-design/icons';
import { useLocation } from 'react-router-dom';
// import type { DatePickerProps } from 'antd';
// import locale from 'antd/es/date-picker/locale/zh_CN';
import { useState, useEffect } from 'react';
import dayjs, { } from 'dayjs';
export default function ProductRelease() {
  const [reasonModalOpen, setReasonModalOpen] = useState(false)  // 未通过原因弹窗
  const [goodsCheckRemark, setGoodsCheckRemark] = useState('') // 未通过原因
  const [messageApi, messageContext] = useMessage();
  const { state } = useLocation()
  // const dateFormat = 'YYYY年MM月DD日';
  const sellBelongType = state ? state.sellBelongType : ''; // 所属人类型
  const sellDate = state ? state.sellDate : '';  // 日期
  // const sellDate = state?dayjs(state.sellDate).format(dateFormat) : '';  // 日期
  const language = state ? state.language : '';  // 开发者语言
  // const sellBoxtype = state ? state.sellBoxtype : ''; //软著类型
  const sellKeywords = state ? state.sellKeywords : ''; // 搜索关键字
  useEffect(() => {
    // console.log('sellBelongType', sellBelongType);
    // console.log('sellDate', sellDate);
    // console.log('language', language);
    // console.log('sellBoxtype', sellBoxtype);
    // console.log('sellKeywords', sellKeywords);
    // if (sellDate) {
    //   console.log('sellDate', dayjs(sellDate).year());
    // }

    setPage(1)
    getGoodsDate(1)
  }, [state])
  const height = window.innerHeight - 180;
  // const [messageApi, contextHolder] = message.useMessage();

  // const [belongType, setBelongType] = useState<any>() // 所属人类型
  // const [date, setDate] = useState<any>()  // 日期
  // const [language, setLanguage] = useState<any>()  // 开发者语言
  // const [type, setType] = useState<any>() //软著类型
  const [page, setPage] = useState(1) // 分页
  const [total, setTotal] = useState(0) // 总条数
  const [editModalOpen, setEditModalOpen] = useState(false)  // 控制编辑弹窗
  const [delModalOpen, setDelModalOpen] = useState(false)   // 控制删除弹窗
  const [sellModalOpen, setSellModalOpen] = useState(false)  // 控制上架弹窗
  const [offModalOpen, setOffModalOpen] = useState(false)  // 控制下架弹窗
  const [id, setId] = useState<any>('')  // 编辑id
  const [loading, setLoading] = useState(false)  // 加载


  const [data, setData] = useState<any>([])
  // 点击编辑
  const edit = (item: any) => {
    // console.log(item.goodsId);
    setEditModalOpen(true)
    setId(item.goodsId)
  };
  // 删除id
  const [delId, setDelId] = useState('')
  // 删除商品名字
  // const [delName, setDelName] = useState('')
  // 点击删除
  const del = (item: any) => {
    // console.log(item.order);
    setDelId(item.goodsId)
    // setDelName(item.goodsName)
    setDelModalOpen(true)
  };
  // 点击确定删除
  const delOk = async () => {
    try {
      await deleteGoods(delId)
      // setData((prevData: any) => {
      //   return prevData.filter((dataItem: any) => dataItem.goodsId !== delId)
      // })

      setDelModalOpen(false)
      messageApi.open({
        type: 'success',
        content: '删除成功',
      })
      getGoodsDate(page)

    } catch (error: any) {

      if (error.response) {
        const data = error.response.data;
        messageApi.open({
          type: 'error',
          content: data.msg ? data.msg : `${data.path}(${data.status})`,
        });
      } else {
        console.error(error)
      }
    }
  }
  // 下架id
  const [offId, setOffId] = useState('')
  // 下架商品名字
  const [offName, setOffName] = useState('')
  // 点击下架
  const off = (item: any) => {
    setOffId(item.goodsId)
    setOffName(item.goodsName)
    setOffModalOpen(true)
  };
  // 点击确定下架
  const offOk = async () => {
    try {
      await putOffShelf(offId)

      setData((prevData: any) => {
        return prevData.map((dataItem: any) => {
          if (dataItem.goodsId === sellId) {
            return {
              ...dataItem,
              goodsStatus: 0
            };
          }
          return dataItem;
        });

      })
      setOffModalOpen(false)
      messageApi.open({
        type: 'success',
        content: '下架成功',
      })
    } catch (error: any) {

      if (error.response) {
        const data = error.response.data;
        messageApi.open({
          type: 'error',
          content: data.msg ? data.msg : `${data.path}(${data.status})`,
        });
      } else {
        console.error(error)
      }
    }
  }
  // 上架id
  const [sellId, setSellId] = useState('')
  // 上架商品名字
  const [sellName, setSellName] = useState('')
  // 点击上架
  const sell = (item: any) => {
    setSellId(item.goodsId)
    setSellName(item.goodsName)
    setSellModalOpen(true)
  };
  // 点击确定上架
  const sellOk = async () => {
    try {
      await putOnShelf(sellId)
      setData((prevData: any) => {
        return prevData.map((dataItem: any) => {
          if (dataItem.goodsId === sellId) {
            return {
              ...dataItem,
              goodsStatus: '1'
            };
          }
          return dataItem;
        });

      })
      setSellModalOpen(false)
      messageApi.open({
        type: 'success',
        content: '上架成功',
      })
    } catch (error: any) {

      if (error.response) {
        const data = error.response.data;
        messageApi.open({
          type: 'error',
          content: data.msg ? data.msg : `${data.path}(${data.status})`,
        });
      } else {
        console.error(error)
      }
    }
  }

  const [submitModalOpen, setSubmitModalOpen] = useState(false)  // 控制提交审核弹窗
  const [submitId, setSubmitId] = useState('') // 提交审核id
  const [submitName, setSubmitName] = useState('') // 提交审核名字
  // 点击提交审核
  const submit = async (item: any) => {
    // console.log(item);
    setSubmitName(item.goodsName)
    setSubmitId(item.goodsId)
    setSubmitModalOpen(true)
  };
  // 点击确定提交
  const submitAuditOk = async () => {
    try {
      await submitAudit(submitId)
      setData((prevData: any) => {
        return prevData.map((dataItem: any) => {
          if (dataItem.goodsId === submitId) {
            return {
              ...dataItem,
              goodsCheckStatus: 1
            };
          }
          return dataItem;
        });
      });
      setSubmitModalOpen(false)
      messageApi.open({
        type: 'success',
        content: '提交审核成功',
      })
    } catch (error: any) {

      if (error.response) {
        const data = error.response.data;
        messageApi.open({
          type: 'error',
          content: data.msg ? data.msg : `${data.path}(${data.status})`,
        });
      } else {
        console.error(error)
      }
    }
  }

  const [selectTypeArray, setSelectTypeArray] = useState<any>([]) // 选择的软著类型

  const getGoodsDate = async (page: number) => {
    try {
      setLoading(true)
      const res: any = await getGoodsList({
        page: page,
        rows: 20,
        // sellBelongType: sellBelongType,
        // sellDate: sellDate,
        // language: language,
        // sellBoxtype: sellBoxtype,
        // sellKeywords: sellKeywords,
        keywords: sellKeywords ? sellKeywords : '',
        goodsLeaderType: sellBelongType ? sellBelongType : '',
        goodsGetTime: sellDate ? dayjs(sellDate).year() : '',
        goodsDevelop: language ? language : '',
        // goodsType: sellBoxtype ? sellBoxtype.join(',') : '',
        goodsType: selectTypeArray.length > 0 ? selectTypeArray.join(',') : '',
      })

      setPage(res.page)
      setData(res.rows)
      setTotal(res.total)
      setLoading(false)
      // console.log(res);
      if (res.rows.length <= 0) {
        if (page > 1) {
          setPage(page - 1)
          getGoodsDate(page - 1)
        }
      }
    } catch (error: any) {

      if (error.response) {
        const data = error.response.data;
        messageApi.open({
          type: 'error',
          content: data.msg ? data.msg : `${data.path}(${data.status})`,
        });
      } else {
        console.error(error)
      }
    } finally {
      setLoading(false)
    }

  }
  const [softTypeList, setSoftTypeList] = useState<any>([]) // 软著类型列表
  // 获取软著类型列表
  const getSoftTypeListDate = async () => {
    try {
      const res: any = await getSoftTypeList()
      // console.log('软著类型列表', res);
      // setSoftTypeList(res.map((item: any) => {
      //     return {
      //         value: item.dataId,
      //         label: item.dataName,
      //     }
      // }))
      setSoftTypeList(res)
    } catch (error: any) {

      if (error.response) {
        const data = error.response.data;
        messageApi.open({
          type: 'error',
          content: data.msg ? data.msg : `${data.path}(${data.status})`,
        });
      } else {
        console.error(error)
      }
    }
  }
  useEffect(() => {
    getGoodsDate(page)
  }, [page, selectTypeArray])

  useEffect(() => {
    getSoftTypeListDate()
  }, [])
  return (
    <div className='product-release' style={{ height: `${height}px`, overflow: 'auto' }}>
      {messageContext}

      <div>
        {/* 表格 */}
        <div className='product-release-table' style={{ height: `${height - 80}px` }}>

          <Spin tip="正在加载..." size="small" spinning={loading}>
            <div style={{ height: `${height - 80}px`, overflow: 'auto', position: 'relative' }}>
              <div className='goodsTypeArrayBox'>
                <div className='goodsTypeTitle'>软著类型 : </div>
                <div className='goodsTypeArray'>
                  {softTypeList.map((item: any) => {
                    return (
                      <div className='typeName'
                        key={item.dataId}
                        style={{
                          color: selectTypeArray.includes(item.dataId)? '#E73B3B' : '#707070',
                        }}
                        onClick={()=>{
                          if (selectTypeArray.includes(item.dataId)) {
                            setSelectTypeArray(selectTypeArray.filter((typeId: any) => typeId !== item.dataId)) 
                          }else{
                            setSelectTypeArray([...selectTypeArray, item.dataId])
                          }
                        }}
                        >
                        {item.dataName}
                      </div>
                    )
                  })}

                </div>
              </div>
              {/* {data.length <= 0 ? (
                <div className='nodata' style={{ height: `${height - 93}px` }}>
                  <Empty
                    description={
                      '暂无数据'
                    } />
                </div>) : (
                <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                  <thead >
                    <tr style={{ background: '#F7F7F7', height: 32, fontSize: 14 }}>
                      <th style={{ width: 50 }}>序号</th>
                      <th style={{ width: 110 }}></th>
                      <th>软著名称</th>
                      <th>软著版本</th>
                      <th>售卖价格</th>
                      <th>截止售卖时间</th>
                      <th>平台审核</th>
                      <th>操作</th>
                    </tr>
                  </thead>
                  <tbody style={{ color: '#888888' }}>
                    {data.map((item: any, index: any) => {
                      return (
                        <React.Fragment key={item.goodsId}>
                          <tr style={{ height: 15 }}>
                            <td colSpan={9} style={{ border: 'none' }}>

                            </td>
                          </tr>
                          <tr style={{ background: '#F7F7F7', height: 45 }}>
                            <td colSpan={9}>

                              <span style={{ marginLeft: 55 }}>
                                编号 :  {item.goodsNumber}
                              </span>
                              <span style={{ marginLeft: 45 }}>
                                软著取得时间 :  {item.goodsGetTime}
                              </span>
                            </td>
                          </tr>
                          <tr style={{ textAlign: 'center', height: 110, maxWidth: 110 }}>
                            <td>{(page - 1) * 10 + index + 1}</td>
                            <td className='product-release-table-img-td'>
                              <div className='product-release-table-img'>
                                <Image src={showImage(item.goodsPhoto, false)} height={90} preview={{
                                  mask: '查看',

                                }}
                                  style={{ maxWidth: '100%' }}
                                ></Image>
                              </div>
                            </td>
                            <td className='product-release-table-name-td'>

                              {item.goodsName}

                            </td>
                            <td>{item.goodsVersion}</td>
                            <td style={{ fontSize: 24, color: '#FF5D15' }}>{item.goodsPrice}</td>
                            <td>{item.goodsLastTime}</td>

                            <td style={{
                              fontWeight: 'bold',
                            }}>
                              {item.goodsCheckStatus == '0' ?
                                <div>
                                  <div style={{
                                    color: 'red',
                                    cursor: 'pointer',
                                  }}
                                    title='点击查看未通过原因'
                                    onClick={() => {
                                      setGoodsCheckRemark(item.goodsCheckRemark)
                                      setReasonModalOpen(true)

                                    }}
                                  > 未通过 </div>
                                  <div style={{
                                    fontSize: 12
                                  }}>(点击查看原因)</div>
                                </div>
                                : item.goodsCheckStatus == '1' ?
                                  <span style={{ color: 'skyBlue' }}> 审核中 </span>
                                  : item.goodsCheckStatus == '2' ?
                                    <span style={{ color: 'green' }}> 已通过  </span>
                                    : '未提交'}</td>
                            <td style={{
                              width: 250,
                            }}>
                              <div>
                                <span className='product-release-table-btn'
                                  style={{
                                    display: item.goodsStatus == '1' ? 'none' : 'unset'
                                  }}
                                  onClick={() => {
                                    edit(item)
                                  }}>编辑</span>
                                <span className='product-release-table-btn product-btn' style={{
                                  display: item.goodsCheckStatus == '1' || item.goodsCheckStatus == '2' ? 'none' : 'unset'
                                }} onClick={() => submit(item)}>提交审核</span>
                                <span className='product-release-table-btn product-btn ' style={{

                                  display: item.goodsStatus == 0 ? 'unset' : 'none'

                                }} onClick={() => del(item)}>删除</span>
                                <span className='product-release-table-btn product-btn ' style={{
                                  display: item.goodsStatus == '0' && item.goodsCheckStatus == '2' ? 'unset' : 'none'
                                }} onClick={() => sell(item)}>上架</span>
                                <span className='product-release-table-btn product-btn '
                                  style={{
                                    display: item.goodsStatus == '0' || item.goodsOrderStatus == '1' ? 'none' : 'unset'
                                  }}
                                  onClick={() => off(item)}>下架</span>
                                <span style={{
                                  display: item.goodsOrderStatus == '1' ? 'unset' : 'none',
                                }}>
                                  正在交易中...
                                </span>
                              </div>
                            </td>
                          </tr>
                        </React.Fragment>

                      )
                    })}

                  </tbody>
                </table>
              )
              } */}

              {data.length <= 0 ? (
                <div className='nodata' style={{ height: `${height - 93}px` }}>
                  <Empty
                    description={
                      '暂无数据'
                    } />
                </div>) : (
                <div className='showGoodsBox'>
                  {data.map((item: any) => {
                    return (
                      <div className='goodSBox' key={item.goodsId}>
                        <div className='delBtn' title='删除'
                          style={{
                            display: item.goodsStatus == 0 ? 'unset' : 'none'
                          }}
                          onClick={
                            () => del(item)
                          }>
                          <div className='delBtnIcons'>
                            <DeleteOutlined />
                          </div>
                        </div>

                        <div className='goodsImg'>
                          <Image src={showImage(item.goodsPhoto, false)} width={'100%'} preview={{
                            mask: '查看',

                          }}
                            style={{ maxWidth: '100%' }}
                          ></Image>
                        </div>
                        <div className='goodsBot'>
                          <div className='goodsPrice'>
                            <div>
                              <span style={{
                                fontSize: 20,
                              }}>￥</span>
                              <span>{item.goodsPrice}</span>
                            </div>
                            <div className='goodsStatus' >
                              {item.goodsCheckStatus == '0' ?
                                <div>
                                  <div style={{
                                    color: 'red',
                                    cursor: 'pointer',
                                  }}
                                    title='点击查看未通过原因'
                                    onClick={() => {
                                      setGoodsCheckRemark(item.goodsCheckRemark)
                                      setReasonModalOpen(true)

                                    }}
                                  > 未通过 </div>
                                  {/* <div style={{
                                    fontSize: 12
                                  }}>(点击查看原因)</div> */}
                                </div>
                                : item.goodsCheckStatus == '1' ?
                                  <span style={{ color: 'skyBlue' }}> 审核中 </span>
                                  : item.goodsCheckStatus == '2' ?
                                    <span style={{ color: 'green' }}> 已通过  </span>
                                    : <span style={{ color: 'rgb(155, 155, 155)' }}> 未提交  </span>}
                            </div>

                          </div>
                          <div className='goodsNameBox'>
                            {/* <div className='tipsPrice'>特价</div> */}
                            <div className='goodsName' title={item.goodsName}>{item.goodsName}</div>
                          </div>
                          <div className='goodsTime'>
                            截止日期 : {item.goodsLastTime}
                          </div>
                          <div className='goodsBtnBox'>
                            <Button className='goodsBtn' style={{
                              display: item.goodsStatus == '1' ? 'none' : 'unset'
                            }}
                              onClick={() => {
                                edit(item)
                              }}>编辑</Button>
                            <Button className='goodsBtn' type="primary" style={{
                              display: item.goodsCheckStatus == '1' || item.goodsCheckStatus == '2' ? 'none' : 'unset'
                            }} onClick={() => submit(item)}>提交审核</Button>
                            <Button className='goodsBtn' type="primary" style={{
                              display: item.goodsStatus == '0' && item.goodsCheckStatus == '2' ? 'unset' : 'none'
                            }} onClick={() => sell(item)}>上架</Button>
                            <Button className='goodsBtn' type="primary" style={{
                              display: item.goodsStatus == '0' || item.goodsOrderStatus == '1' ? 'none' : 'unset'
                            }}
                              onClick={() => off(item)}>下架</Button>
                            <div className='goodsBtnIng' style={{
                              display: item.goodsOrderStatus == '1' ? 'unset' : 'none'
                            }}>
                              正在交易中...
                            </div>
                          </div>
                        </div>
                      </div>
                    )
                  })}

                  {/* <div className='goodSBox'>
                    <div className='goodsImg'>

                    </div>
                    <div className='goodsBot'>
                      <div className='goodsPrice'>
                        <span style={{
                          fontSize: 20,
                        }}>￥</span>
                        <span>299</span>
                      </div>
                      <div className='goodsNameBox'>
                        <div className='tipsPrice'>特价</div>
                        <div className='goodsName' title='智能化接口处理系统'>智能化接口处理系统</div>
                      </div>
                      <div className='goodsTime'>
                        2025-05-12
                      </div>
                      <div className='goodsBtnBox'>
                        <div className='goodsBtn'>编辑</div>
                        <div className='goodsBtn'>提交审核</div>
                      </div>
                    </div>
                  </div> */}

                </div>
              )
              }

            </div>
          </Spin>

          {/* )} */}

        </div>


        {/* defaultCurrent: 默认当前页数  total:数据总数 defaultPageSize:'页面显示几条'  */}
        <div className='product-release-pagination'>
          <Pagination
            showSizeChanger={false}
            current={page} total={total} defaultPageSize={20} onChange={(page) => {
              // console.log(page)
              setPage(page)
            }} />
        </div>
      </div>

      {/* 编辑弹窗 */}
      <Modal title={'编辑'}
        destroyOnClose={true}
        open={editModalOpen}
        footer={null} // 将 footer 设置为 null 来隐藏自带按钮
        width={1152}
        onCancel={() => {
          setEditModalOpen(false);
        }}
        centered
      >
        {/* <div style={{ height: `${height - 20}px`, overflow: 'auto', borderTop: '1px solid #e8e8e8' }}> */}
        <EditModal closeModal={() => { setEditModalOpen(false) }}
          getGoodsDate={getGoodsDate}
          id={id}
        ></EditModal>
        {/* </div> */}
      </Modal>
      {/* 删除弹窗 */}
      <Modal title="删除"
        okText="确认"
        cancelText="取消"
        destroyOnClose={true}
        open={delModalOpen}
        onOk={() => {
          // setDelModalOpen(false)
          delOk()
        }}
        onCancel={() => {
          setDelModalOpen(false)
        }}
        okButtonProps={{ style: { background: 'red', color: 'white' } }}
        style={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          height: `${height}px`,
        }}>
        <div style={{
          width: 700,
          marginTop: 20
        }}>
          删除后这条信息将不被保存，确定删除
          {/* {delName} */}
          吗？
        </div>
      </Modal>
      {/* 出售弹窗 */}
      <Modal title="上架"
        okText="确认"
        cancelText="取消"
        destroyOnClose={true}
        open={sellModalOpen}
        onOk={() => {
          // setSellModalOpen(false)
          sellOk()
        }}
        onCancel={() => {
          setSellModalOpen(false)
        }}
        okButtonProps={{ style: { background: '#28915A', color: 'white' } }}
        style={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          height: `${height}px`,
        }}>
        <div style={{
          width: 700,
          marginTop: 20
        }}>
          确定将{sellName}上架吗？
        </div>
      </Modal>
      <Modal title="下架"
        okText="确认"
        cancelText="取消"
        destroyOnClose={true}
        open={offModalOpen}
        onOk={() => {
          // setSellModalOpen(false)
          offOk()
        }}
        onCancel={() => {
          setOffModalOpen(false)
        }}
        okButtonProps={{ style: { background: '#28915A', color: 'white' } }}
        style={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          height: `${height}px`,
        }}>
        <div style={{
          width: 700,
          marginTop: 20
        }}>
          确定将{offName}下架吗？
        </div>
      </Modal>
      <Modal title="提交审核"
        okText="确认"
        cancelText="取消"
        destroyOnClose={true}
        open={submitModalOpen}
        onOk={() => {
          submitAuditOk()

        }}
        onCancel={() => {

          setSubmitModalOpen(false)
        }}
        // okButtonProps={{ style: { background: 'red', color: 'white' } }}
        style={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          height: `${height}px`,
        }}>
        <div style={{
          width: 700,
          marginTop: 20
        }}>
          确定将{submitName}提交审核吗?
        </div>
      </Modal>
      <Modal title="未通过原因"
        okText="确认"
        cancelText="取消"
        destroyOnClose={true}
        open={reasonModalOpen}
        onOk={() => {
          // submitAuditOk()

        }}
        footer={null}
        onCancel={() => {
          setReasonModalOpen(false)
        }}
        // okButtonProps={{ style: { background: 'red', color: 'white' } }}
        style={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          height: `${height}px`,
        }}>
        <div style={{
          width: 700,
          // marginTop: 20
          padding: '20px 0px',
        }}>
          {goodsCheckRemark}

        </div>
      </Modal>
    </div>
  )
}

