/*
 * @Author: cclu
 * @Date: 2022-03-04 10:51:49
 * @LastEditTime: 2024-09-30 17:50:35
 * @LastEditors: cclu 1106109051@qq.com
 * @Description: 合作方分润 组件
 * @FilePath: \cloud-platform\src\pages\BussinessProject\components\ShareBenefit.tsx
 */
import { useRef, useState } from 'react';
import { Drawer, message, Space } from 'antd';
import ProTable from '@ant-design/pro-table';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import type { BusinessProjectModel, RevenueConfirmModel } from '../data';
import { createRevenueAccount, getRevenuenConfirmList, handleAgain, handleGetSplitRes } from '../service'
import RevenueList from './RevenueList';
import moment from 'moment';
import { fmoney } from "@/services/options";
import { getDetail } from "@/pages/contract/service";
import Item from 'antd/lib/list/Item';

// 更新回款信息
const handleAddUpdate = async (dataType: 1000 | 2000, fields: number) => {
  const hide = message.loading('正在提交...');
  // dataType 经营模式为合作经营（1000）时
  const result = await createRevenueAccount(fields as number);
  hide();
  if (result.Result_Code !== 100) {
    message.error(`${result.Result_Desc}` || `${result.Result_Code}:提交失败`);
    return false;
  }
  message.success("生成账款记录成功！")
  return true;
};

/**
 * @description: 合作方分润
 * @param {BusinessProjectModel} props 项目详情数据对象
 * @return {*}
 */
const ShareBenefit: React.FC<{ props: BusinessProjectModel, showEdit?: boolean, startDate?: string, endDate?: string, otherDate?: any }> = (
  { props, showEdit, startDate, endDate, otherDate, showType, relatedContractsList }: { props: BusinessProjectModel, showEdit?: boolean, startDate?: string, endDate?: string, otherDate?: any, showType?: any, relatedContractsList?: any }) => {
  // const { SERVERPARTSHOP_ID, SERVERPARTSHOP_NAME } = props
  const actionRef = useRef<ActionType>() // 表格对应的对象
  const [showDetail, setShowDetail] = useState<boolean>(false) // 是否显示详情
  const [currentRow, setCurrentRow] = useState<BusinessProjectModel | any>(undefined) // 选中的当前行
  const [tableLoading, setTableLoading] = useState<boolean>(false)
  // 关联合同需要遍历的表格
  const [relateTableData, setRelateTableData] = useState<any>()
  const revenuenColumns: any = [
    {
      title: '开始日期',
      dataIndex: 'STARTDATE',
      valueType: "date",
      width: 110,
      align: 'center',
      sorter: (a, b) => (new Date(a.STARTDATE).getTime() || 0) - (new Date(b.STARTDATE).getTime() || 0),
      defaultSortOrder: 'descend'
    },
    {
      title: '结束日期',
      dataIndex: 'ENDDATE',
      valueType: "date",
      width: 110,
      align: 'center'
    },
    {
      title: '真实提成',
      dataIndex: '',
      valueType: 'digit',
      align: "center",
      hideInTable: props.BUSINESS_TYPE === 2000,
      width: 110,
      render: (_, record) => {
        return <span style={{
          color: record.REVENUE_AMOUNT ?
            ((record.ROYALTY_THEORY / record.REVENUE_AMOUNT) * 100) >= record.GUARANTEERATIO ? 'red' : 'green'
            : ''
        }}>
          {record.REVENUE_AMOUNT ? `${((record.ROYALTY_THEORY / record.REVENUE_AMOUNT) * 100).toFixed(2)}%` : '-'}
        </span>
      },
    },
    {
      title: '实际营业额',
      dataIndex: 'REVENUE_AMOUNT',
      valueType: "money",
      width: 140,
      align: "right",
      render: (_, record) => {
        return <a onClick={() => { // 点击实际营业额时 打开抽屉 展示每日营收数据
          console.log('record', record)
          setCurrentRow(record)
          setShowDetail(true)
        }}>{record.REVENUE_AMOUNT ? fmoney(record.REVENUE_AMOUNT, 2) : '-'}</a>
      },
    },
    {
      title: '合同提成',
      dataIndex: 'GUARANTEERATIO',
      valueType: 'digit',
      align: "center",
      hideInTable: props.BUSINESS_TYPE === 2000,
      width: 110,
      render: (_, record) => {
        return `${record.GUARANTEERATIO || '-'}%`
      },
    },
    {
      title: '保底租金',
      dataIndex: 'MINTURNOVER',
      valueType: "money",
      width: 140,
      align: "center",
      render: (_, record) => {
        return <span style={{ color: record.MINTURNOVER ? '' : '#faad14' }}>{record.MINTURNOVER ? `¥${fmoney(record.MINTURNOVER, 2)}` : '合同期外'}</span>
      }
    },
    {
      title: '甲方到账',
      dataIndex: 'ROYALTY_PRICE',
      valueType: "money",
      align: "right",
      width: 140,
      render: (_, record) => {
        return <span>{record.ROYALTY_PRICE ? `¥${fmoney(record.ROYALTY_PRICE, 2)}` : '-'}</span>
      }
    },
    {
      title: '甲方入账',
      dataIndex: 'ROYALTY_THEORY',
      valueType: "money",
      align: "right",
      width: 140,
      render: (_, record) => {
        return <span>{record.ROYALTY_THEORY ? `¥${fmoney(record.ROYALTY_THEORY, 2)}` : '-'}</span>
      }
    },
    {
      title: '乙方入账',
      dataIndex: 'SUBROYALTY_THEORY',
      valueType: "money",
      align: "right",
      width: 140,
      render: (_, record) => {
        return <span>{record.SUBROYALTY_THEORY ? `¥${fmoney(record.SUBROYALTY_THEORY, 2)}` : '-'}</span>
      }
    },
    // {
    //     title: '丙方入账',
    //     dataIndex: 'PARTYC_SHAREPROFIT',
    //     valueType: "money",
    //     width: 100,

    // },
    {
      title: '备注说明',
      dataIndex: 'BIZPSPLITMONTH_DESC',
      ellipsis: true,
      hideInTable: !(showEdit === undefined || showEdit),
    },
    // {
    //   title: '商家欠款',
    //   dataIndex: '',
    //   ellipsis: true,
    //   render:(_,record)=>{
    //      return <span style={{color:'red'}}>{record?.SUBROYALTY_PRICE===record?.SUBROYALTY_THEORY?'-':fmoney(record?.SUBROYALTY_PRICE - record?.SUBROYALTY_THEORY,2)}</span>
    //   }
    // },
    {
      title: '操作',
      valueType: 'option',
      width: 80,
      hideInTable: showType === 'Nooperate' ? true : !(showEdit === undefined || showEdit),
      render: (_, record) => (
        new Date(record?.STARTDATE).getTime() < new Date().getTime() && record.showAgainBtn ?
          <Space>
            <a
              key="revenue"
              onClick={async () => {
                // const amount1000 = await handleAddUpdate(1000,
                //     record?.SHOPROYALTY_ID ? record?.SHOPROYALTY_ID : 0)
                // if (amount1000) {
                //     actionRef.current?.reload()
                // }
                setTableLoading(true)

                let req = {}
                const yesterday = moment().subtract(1, 'day').startOf('day').format('YYYY-MM-DD')
                if (new Date(yesterday).getTime() < new Date(moment(record.ENDDATE).format('YYYY-MM-DD')).getTime()) {
                  req = {
                    StartDate: moment(record.STARTDATE).format('YYYY-MM-DD'),
                    EndDate: moment(yesterday).format('YYYY-MM-DD'),
                    ProjectId: props.BUSINESSPROJECT_ID,
                    // OutBusinessType:props.BUSINESS_TYPE
                  }
                } else {
                  req = {
                    StartDate: moment(record.STARTDATE).format('YYYY-MM-DD'),
                    EndDate: moment(record.ENDDATE).format('YYYY-MM-DD'),
                    ProjectId: props.BUSINESSPROJECT_ID,
                    // OutBusinessType:props.BUSINESS_TYPE
                  }
                }
                const data = await handleAgain(req)
                setTableLoading(false)
                if (data.Result_Code === 100) {
                  actionRef.current?.reload()
                  message.success(data.Result_Desc)
                } else {
                  message.error(data.Result_Desc)
                }
              }}
            >
              重新生成
            </a>
          </Space> : ''
      ),
    },
  ]

  const relateRevenuenColumns: any = [
    ...revenuenColumns.slice(0, 9)
  ]

  // 拿到关联合同项目数据
  const handleGetRelatedData = async (list: any) => {
    console.log('list', list);

    let result: any = []


    // 可能存在多个关联项目
    for (let i = 0; i <= list.length - 1; i++) {
      const res = await handleGetSplitRes({
        DataType: 2,
        CompactId: list[i].REGISTERCOMPACT_ID
      })
      result.push({
        title: list[i].COMPACT_NAME,
        time: `${moment(list[i].COMPACT_STARTDATE).format('YYYY-MM-DD')}-${moment(list[i].COMPACT_ENDDATE).format('YYYY-MM-DD')}`,
        STARTDATE: moment(list[i].COMPACT_STARTDATE).format('YYYY-MM-DD'),
        ENDDATE: moment(list[i].COMPACT_ENDDATE).format('YYYY-MM-DD'),
        data: res.data
      })
      // .then(res => {
      //   console.log('312321312312', JSON.parse(JSON.stringify(res)));
      //   result.push({
      //     title: list[i].COMPACT_NAME,
      //     time: `${moment(list[i].COMPACT_STARTDATE).format('YYYY-MM-DD')}-${moment(list[0].COMPACT_ENDDATE).format('YYYY-MM-DD')}`,
      //     data: res.data
      //   })
      //   console.log('resultresultresultresult', result);
      //   // for循环不一定会等接口调完  才赋值 所以放在循环里面 最后一次也会拿到最新的

      // })
    }
    setRelateTableData(result)
    return result
  }

  return (
    <>
      <ProTable<RevenueConfirmModel>
        cardProps={{  // 去除表格内边距
          bodyStyle: { padding: 0 }
        }}
        rowKey="REVENUECONFIRM_ID"
        actionRef={actionRef}
        loading={tableLoading}
        request={async (pramas, sorter) => {
          console.log('otherDate', otherDate);

          setTableLoading(true)
          const sortstr = Object.keys(sorter).map(n => {
            const value = sorter[n]
            return value ? `${n} ${value.replace('end', '')}` : ''
          })
          let req = {}
          if (new Date(props?.PROJECT_STARTDATE).getTime() > new Date(otherDate).getTime()) {
            req = {
              ...pramas,
              BusinessProjectId: props.BUSINESSPROJECT_ID,
              DataType: 2,
              BusinessDate: moment(otherDate).format('YYYY-MM-DD')
            }
          } else {
            req = {
              ...pramas,
              BusinessProjectId: props.BUSINESSPROJECT_ID,
              DataType: 2,
            }
          }
          const data = await handleGetSplitRes(req)
          console.log('fjajasdaslkd', data);

          let res: any = []
          if (relatedContractsList && relatedContractsList.length > 0) {
            res = await handleGetRelatedData(relatedContractsList)
          }

          console.log('resresresresres', res);
          if (res && res.length > 0) {
            res.forEach((item: any) => {
              if (data.data && data.data.length > 0) {
                data.data.forEach((subItem: any) => {
                  if (new Date(item.STARTDATE).getTime() < new Date(subItem.ENDDATE).getTime() && new Date(item.ENDDATE).getTime() >= new Date(subItem.ENDDATE).getTime()) {
                    // 如果该行数据(上面的)  已经包括了下面的数据的时间 那么这段就不出现重新生成 
                  } else {
                    subItem.showAgainBtn = true
                  }
                })
              }
            })
          } else {
            data.data.forEach((subItem: any) => {
              subItem.showAgainBtn = true
            })
          }


          setTableLoading(false)
          return data
        }}
        options={false}
        columns={revenuenColumns}
        search={false}
        pagination={false}
      />

      <div style={{ marginTop: '24px' }}>
        {
          relateTableData && relateTableData.length > 0 ?
            relateTableData.map((item: any) => {
              return <div>
                <div style={{ paddingLeft: '12px', marginBottom: '8px' }}>{item.title ? item.title + '：' : ''}{item.time || ''}</div>
                <ProTable
                  search={false}
                  pagination={false}
                  columns={relateRevenuenColumns}
                  options={false}
                  dataSource={item.data}
                />
              </div>
            }) : ''
        }
      </div>


      {/* 查看项目详情 右侧弹出的抽屉 */}
      <Drawer
        width="80%"
        // className="project-drawer"
        visible={showDetail} // 抽屉弹框是否显示状态
        onClose={() => { // 关闭抽屉 设置抽屉状态为关闭
          setShowDetail(false);
        }}
        bodyStyle={{ backgroundColor: "#f9f9f9", padding: 0 }}
        closable={false}
      >
        {/* 抽屉打开时 加载项目详情组件 */}
        {showDetail && <RevenueList BusinessProjectId={props.BUSINESSPROJECT_ID} propsBP={props} propsRC={currentRow}
          ShopRoyaltyId={currentRow?.SHOPROYALTY_ID ? currentRow?.SHOPROYALTY_ID : 0}
          ShopIds={currentRow?.SERVERPARTSHOP_ID ? currentRow?.SERVERPARTSHOP_ID : ''}
          StartDate={moment(currentRow?.STARTDATE).format('YYYY-MM-DD')}
          EndDate={moment(currentRow?.ENDDATE).format('YYYY-MM-DD')} onShow={showDetail}></RevenueList>}
      </Drawer>
    </>
  );
}
export default ShareBenefit;
