/*
 * @Author: your name
 * @Date: 2022-04-28 10:47:35
 * @LastEditTime: 2024-08-23 15:25:03
 * @LastEditors: cclu 1106109051@qq.com
 * @Description: 经营商户相关联系人管理组件 未对接接口
 * @FilePath: \cloud-platform\src\pages\basicManage\Merchats\components\LinkManTable.tsx
 */
import useRequest from '@ahooksjs/use-request';
import React, { useImperativeHandle, useRef, useState } from 'react';
import ProTable, { EditableProTable } from '@ant-design/pro-table';

import type { ActionType, ProColumns } from "@ant-design/pro-table";
import type { LinkManModel } from "../data";
import { getBrandList, getTreeList, handleDeleteRTCoopMerchants, handleRTCoopMerchantsList, handleSynchroRTCoopMerchants } from '../service';
import { FormInstance, message } from "antd";
import { Avatar, Button, Col, Menu, Modal, Popconfirm, Row, Image } from "antd";
import { getBusniessBrandTree } from "@/pages/basicManage/service";
import { getFieldEnumTree } from "@/services/options";
import type { INTERFACEModel } from "@/pages/Test/INTERFACE/data";
import { getList } from "@/pages/Test/INTERFACE/service";
import { FileSearchOutlined, PlusOutlined } from "@ant-design/icons";
import { MerchantModel } from "../data";
import { ModalForm, ProFormText } from "@ant-design/pro-form";
import type { BrandModel } from "@/pages/basicManage/Brand/data";
import SubMenu from 'antd/lib/menu/SubMenu';
import Item from 'antd/lib/list/Item';
import moment from 'moment/moment'

const BrandTable = ({ merchartsId, onRef, currentRow }: { merchartsId: number, onRef?: any, currentRow?: any }) => {
  const formRef = useRef<FormInstance>();
  const addFormRef = useRef<FormInstance>();
  const actionRef = useRef<ActionType>();
  const brandActionRef = useRef<ActionType>();

  const { loading, data } = useRequest(async () => {
    if (merchartsId) {
      const data = await getBrandList({ CoopMerchantsId: merchartsId })
      return data
    }
    return []
  })
  const { loadingBrand, data: busiessBrand = [] } = useRequest(getBusniessBrandTree)
  const [modalVisible, setModalVisible] = useState<boolean>(false)
  const [brandVisible, setBrandVisible] = useState<boolean>() // 选择品牌弹出框
  const [brand, setBrand] = useState<BrandModel>() // 选中的品牌
  const [currenMenu, setCurrenMenu] = useState<any>(); // 当前弹出的左侧菜单选中的详细数据
  const [selectedKeys, setSelectedKeys] = useState<any>(); // 当前弹出的左侧菜单选中的ids值

  const [dataSource, setDataSource] = useState<LinkManModel[]>()
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
  if (!loading && !dataSource) {
    setDataSource(data)
  }

  // 根据选中的经营业态查询品牌
  const searchBrand = (item: any) => {
    setSelectedKeys(item.selectedKeys || [])
    const [_, value] = item.key.split('-')
    setCurrenMenu({ 'BRAND_INDUSTRY': value, current: 1 })
    brandActionRef.current?.reload()
  }

  // 生成商户左侧菜单
  const getMenuDom = (data: any[], callback: () => void, noBrand?: boolean) => {
    return (data.map((element: any) => {
      if ((!noBrand && element.BrandTreeList && element.BrandTreeList.length > 0) || element.children) {
        return (
          <SubMenu title={element.BusinessTrade_Name}
            icon={<Avatar src={element.BusinessTrade_ICO} size={16} style={{ marginRight: 4 }} shape="square" />}
            key={`BUSINESSTRADE_ID-${element.BusinessTrade_Id}`}
            onTitleClick={(item) => {
              if (!currenMenu || item.key !== `BUSINESSTRADE_ID-${currenMenu?.BUSINESSTRADE_ID}`) {
                callback.call(callback, item)
              }
              item.domEvent.stopPropagation();
            }}
          >
            {!noBrand && element.BrandTreeList.length > 0 && element.BrandTreeList.map((c: any) =>
              <Menu.Item key={`BRAND_ID-${c.Brand_ID}`}
                icon={<Avatar src={c.Brand_ICO} style={{ backgroundColor: '#fafafa' }} size={22} shape="square" />} >
                {c.Brand_Name}
              </Menu.Item>
            )}
            {element.children && element.children.length > 0 && getMenuDom(element.children, callback, noBrand || undefined)}
          </SubMenu>
        )
      }
      return (<Menu.Item icon={<Avatar src={element.BusinessTrade_ICO} size={16} shape="square" />}
        key={`BUSINESSTRADE_ID-${element.BusinessTrade_Id}`}>{element.BusinessTrade_Name}</Menu.Item>)
    }))
  }

  // 拿到这一次选中的品牌
  const [currentBrand, setCurrentBrand] = useState<any>()


  const columns: ProColumns<any>[] = [
    {
      title: '品牌图标',
      dataIndex: 'LINKER_NAME',
      render: (_, record) => {
        return <Image style={{ width: '20px', height: '20px' }} src={record?.BRAND_ICO} />
      }
    },
    {
      title: '经营业态',
      dataIndex: 'BUSINESSTRADE_NAME',
    },

    {
      title: '经营品牌',
      dataIndex: 'BRAND_NAME',
    },
    {
      title: '操作',
      valueType: 'option',
      width: 160,
      render: (text, record, _, action) => [
        <Popconfirm
          title="确认删除该联系人吗?"
          onConfirm={async () => {
            console.log('delete', record);

            handleDelete(record)
          }}
        >
          <a>删除</a>
        </Popconfirm>
      ],
    }
  ]

  // 删除
  const handleDelete = async (obj: any) => {
    const req: any = {
      RTCoopMerchantsId: obj?.RTCOOPMERCHANTS_ID
    }
    const data = await handleDeleteRTCoopMerchants(req)
    if (data.Result_Code === 100) {
      message.success(data.Result_Desc)
      actionRef.current?.reload()
    } else {
      message.error(data.Result_Desc)
    }
  }

  useImperativeHandle(onRef, () => ({
    dataSource
  }));

  return (
    <>
      <ProTable<INTERFACEModel>
        rowKey={(record) => {
          return `${record?.INTERFACE_ID}`
        }}
        formRef={formRef}
        headerTitle="品牌列表" // 列表表头
        actionRef={actionRef}
        search={false}
        request={async () => {
          if (!merchartsId) {
            return []
          }
          const req: any = {
            CoopMerchantsId: merchartsId
          }
          const data = await handleRTCoopMerchantsList(req)
          console.log('currentBrand', currentBrand);
          console.log('data', data);

          if (data && data.length > 0) {
            setDataSource(data)
            return { data, success: true }
          } else {
            setDataSource([])
            return { data: [], success: true }
          }
        }}
        // dataSource={dataSource}
        columns={columns}
        toolbar={{
          actions: [
            // 新增按钮
            <Button
              key="new"
              icon={<PlusOutlined />}
              type="primary"
              onClick={() => {
                setModalVisible(true)
              }}
            >

            </Button>,
          ],
        }}
        options={false}
        pagination={false}
      />
      <ModalForm
        title={'新建品牌'}
        layout={'horizontal'}
        width={628}
        wrapperCol={{ span: 16 }}
        labelCol={{ span: 6 }}
        formRef={addFormRef}
        visible={modalVisible}
        autoFocusFirstInput
        modalProps={{
          onCancel: () => {
            setModalVisible(false)
            setCurrentBrand(undefined)
          },
        }}
        onVisibleChange={(value) => {

        }}
        onFinish={async (values) => {
          // // 判断有没有品牌数据
          // let dataList: any = brandTableRef.current?.dataSource
          // let resList: any = []
          // if(dataList && dataList.length>0){
          //   dataList.forEach((item: any)=>{
          //     resList.push({
          //       label: item.BRAND_NAME,
          //       value: item.BRAND_ID,
          //       key: '',
          //       type:'',
          //       desc:'',
          //       ico: item.BRAND_INTRO
          //     })
          //   })
          // }
          console.log('CurrentBrand', currentBrand);
          console.log('currentRow', currentRow);



          // 同步商户和品牌的关系列表
          const secondReq: any = {
            COOPMERCHANTS_ID: currentRow?.COOPMERCHANTS_ID,
            BUSINESS_TRADE: currentBrand?.BUSINESS_TRADE,
            BUSINESS_BRAND: currentBrand?.BUSINESS_BRAND,
            OPERATE_DATE: moment().format('YYYY-MM-DD HH:mm:ss')
            // RTCOOPMERCHANTS_ID: '',
            // COOPMERCHANTS_NAME: currentRow?.COOPMERCHANTS_NAME,
            // BUSINESSTRADE_NAME: currentBrand?.BUSINESSTRADE_NAME,
            // BRAND_NAME: currentBrand?.BRAND_NAME,
            // SERVERPART_NAME:'',
            // BRAND_ICO: currentBrand?.BRAND_INTRO,
          }
          const secondData = await handleSynchroRTCoopMerchants(secondReq)
          if (secondData.Result_Code === 100) {
            message.success(secondData.Result_Desc)
            addFormRef.current?.setFieldsValue({ BRAND_NAME: '' })
            setCurrentBrand(undefined)
            setModalVisible(false)
            actionRef.current?.reload()
          } else {
            message.error(secondData.Result_Desc)
          }
        }}
      >
        <ProFormText
          label="经营品牌"
          name="BRAND_NAME"
          placeholder="请选择经营品牌"
          addonAfter={<Button type="primary" icon={<FileSearchOutlined />} onClick={() => {
            setBrandVisible(true)
          }}></Button>}
          // rules={[
          //     {
          //         required: true,
          //         message: '请选择经营品牌',
          //     },
          // ]}
          readonly
        />
      </ModalForm>

      {/* 新增的弹出框 */}
      <Modal visible={brandVisible}
        title="请选择经营业态和品牌"
        width={1024}
        onOk={() => {
          setBrandVisible(false)
          const data = {
            ...brand,
            BUSINESS_BRAND: brand?.BRAND_ID,
            BRAND_NAME: brand?.BRAND_NAME,
          }
          setCurrentBrand(data)
          addFormRef.current?.setFieldsValue(data)
        }}
        onCancel={() => {
          setBrandVisible(false)
          setBrand(undefined)
        }}
        afterClose={() => {
          setCurrenMenu({})
          brandActionRef.current?.reset()
        }}
        bodyStyle={{ padding: 0 }}
      >
        <Row>
          <Col span={6}>
            {
              <Menu
                mode="inline"
                style={{ height: 610, overflowY: 'auto', overflowX: 'hidden' }}
                selectedKeys={selectedKeys}
                onSelect={(item) => {
                  searchBrand(item)
                }}
              >{getMenuDom(busiessBrand, searchBrand, true)}
              </Menu>
            }
          </Col>
          <Col span={18}>
            <ProTable<BrandModel>
              rowKey="BRAND_ID"
              size="small"
              columns={[
                {
                  dataIndex: 'BRAND_INTRO',
                  hideInSearch: true,
                  width: 48,
                  render: (_, record) => {
                    return <Avatar src={_} size={24}>{record.BRAND_NAME.substring(0, 1)}</Avatar>
                  },
                  hideInDescriptions: true,
                },
                {
                  dataIndex: 'BRAND_NAME',
                  title: '品牌名称',
                  hideInSearch: true
                },

                {
                  dataIndex: 'keyWord',
                  title: '品牌名称',
                  hideInTable: true
                  // hideInSearch: true
                },

              ]}

              request={async (params) => {

                if (brandVisible) {
                  const data = await getTreeList({
                    ...params,
                    keyWord: params.keyWord ? { value: params.keyWord, key: 'BRAND_NAME' } : null
                  })
                  return data
                }
                return { data: [], success: true }
              }}
              params={currenMenu}
              search={{ span: 12, }}
              pagination={{ defaultPageSize: 10, size: 'small', showSizeChanger: false }}
              onReset={() => {
                setCurrenMenu({})
                brandActionRef.current?.reload()
              }}
              options={false}
              style={{ minHeight: 610 }}
              actionRef={brandActionRef}
              rowSelection={{

                type: "radio",
                onChange: (selectedRowKeys, selectedRows) => {
                  console.log('selectedRows', selectedRows);
                  setBrand(selectedRows[0])
                }

              }}
              tableAlertRender={false}
            >

            </ProTable>
          </Col>
        </Row>
      </Modal>
    </>


  )
}

export default BrandTable;
