/*
 * @Author: cclu
 * @Date: 2022-04-28 10:47:35
 * @LastEditTime: 2024-12-16 12:04:59
 * @LastEditors: cclu 1106109051@qq.com
 * @Description: 经营商户信息管理
 * @FilePath: \cloud-platform\src\pages\basicManage\Merchats\index.tsx
 */

import { getFieldEnum } from '@/services/options';
import { PlusOutlined } from '@ant-design/icons';
import ProDescriptions from '@ant-design/pro-descriptions';
import { ModalForm, ProFormSelect, ProFormSwitch, ProFormText, ProFormTextArea } from '@ant-design/pro-form';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import type { ProDescriptionsItemProps } from '@ant-design/pro-descriptions';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import type { FormInstance } from 'antd';

import { Button, Col, Drawer, message, Row, Switch, Form } from 'antd';
import { useImperativeHandle, useRef, useState } from 'react';

import LinkManTable from './components/LinkManTable';
import BrandTable from './components/BrandTable';
import type { MerchantModel } from './data';
import { getList, updateMerchants, getShopDetail, getLinkManList } from './service';

import './style.less'
import closeIcon from "@/assets/brand/closeIcon.png";
import storeIcon from '@/assets/brand/storeIcon.png'
import legalPerson from '@/assets/brand/legalPerson.png'
import account from '@/assets/brand/account.png'
import code from '@/assets/brand/code.png'
import brandDesc from '@/assets/brand/brandDesc.png'
import shopIcon from '@/assets/brand/shopIcon.png'
import map from '@/assets/brand/map.png'
import button from '@/assets/brand/button.png'
import phone from '@/assets/brand/phone.png'
import success from '@/assets/brand/success.png'
import effective from "@/assets/brand/effective.png";
import wrong from "@/assets/brand/wrong.png";
import AddEdit from './components/addEdit';
import React from 'react';
import LoadingBox from '@/pages/reports/Finance/businessAnalysis/components/loading';
import PageTitleBox from '@/components/PageTitleBox';
// 更新信息
const handleAddUpdate = async (fields: MerchantModel) => {
  const hide = message.loading('正在提交...');

  const result = await updateMerchants(fields);
  hide();
  if (result.Result_Code !== 100) {
    message.error(`${result.Result_Desc}` || `${result.Result_Code}:提交失败`);
    return false;
  }
  message.success(fields.COOPMERCHANTS_ID ? '更新成功！' : '新建成功！');
  return true;
};
type DetailProps = {
  isComponent?: boolean
  onRef?: any
}

// const MerchatsTable = ({ isComponent, onRef }: DetailProps) => {
const MerchatsTable: React.FC<{ isComponent?: any, onRef?: any }> = (props) => {
  const { isComponent, onRef } = props

  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const brandTableRef = useRef<any>()
  const [currentRow, setCurrentRow] = useState<MerchantModel>();
  const [showDetail, setShowDetail] = useState<boolean>();
  const [modalVisible, handleModalVisible] = useState<boolean>();
  const [showDrawer, setShowDrawer] = useState<boolean>(false)// 是否显示抽屉
  const [detail, setDetail] = useState<any>(); // 抽屉详情
  const [contactsList, setContactsList] = useState<any>([])// 联系人列表
  // 点击商户名称的点击事件的加载效果
  const [detailLoading, setDetailLoading] = useState<boolean>(false)

  const [disabled, setDraggleDisabled] = useState<boolean>() // 是否拖动
  const [bounds, setBounds] = useState<{ left: number, right: number, top: number, bottom: number }>() // 移动的位置
  const draggleRef = React.createRef<any>()
  // 选中的行
  const [selectRow, setSelectRow] = useState<any>()
  // 选中的行详情
  const [selectRowDetail, setSelectRowDetail] = useState<any>()
  const onDraggaleStart = (event, uiData) => {
    const { clientWidth, clientHeight } = window.document.documentElement;
    const targetRect = draggleRef.current?.getBoundingClientRect();
    if (!targetRect) {
      return;
    }
    setBounds({
      left: -targetRect.left + uiData.x,
      right: clientWidth - (targetRect.right - uiData.x),
      top: -targetRect.top + uiData.y,
      bottom: clientHeight - (targetRect.bottom - uiData.y),
    });
  };

  const columns: ProColumns<MerchantModel>[] = [
    {
      title: '查询条件',
      dataIndex: 'searchKey',
      hideInTable: true,
      hideInDescriptions: true,
      fieldProps: {
        placeholder: "请输入商户名称/统一信用代码"
      }
    },
    {
      dataIndex: 'COOPMERCHANTS_NAME',
      title: '商户名称',
      hideInSearch: true,
      hideInDescriptions: true,
      sorter: true,
      render: (_, record) => {
        return <a
          onClick={async () => {
            setShowDrawer(true)
            await handleGetDetailData(record)
          }}
        >
          {record.COOPMERCHANTS_NAME}
        </a>
      }
    },
    {
      dataIndex: 'COOPMERCHANTS_EN',
      title: '简称',
      hideInSearch: true,
      hideInTable: true,
    },
    {
      dataIndex: 'MERCHANTTYPE_NAME',
      title: '类别',
      hideInSearch: true,
      hideInTable: true,
    },
    {
      dataIndex: 'LINKER_NAME',
      title: '联系人',
      align: 'center',
      width: 100,
      hideInSearch: true,
    },
    {
      dataIndex: 'LINKER_MOBILEPHONE',
      title: '联系方式',
      align: 'center',
      width: 150,
      hideInSearch: true,
    },
    {
      dataIndex: 'TAXPAYER_IDENTIFYCODE',
      title: '统一信用代码',
      hideInTable: true,
      hideInSearch: true,
    },
    {
      dataIndex: 'COOPMERCHANTS_NATURE',
      title: '商户性质',
      valueType: 'select',
      valueEnum: { 1000: '企业', 2000: '个体', 3000: '自然人' },
      hideInTable: true,
      hideInSearch: true,
    },
    {
      dataIndex: 'BANK_NAME',
      title: '开户行',
      // width: 350,
      hideInSearch: true,
    },
    {
      dataIndex: 'BANK_ACCOUNT',
      title: '银行账号',
      width: 200,
      hideInSearch: true,
    },
    {
      dataIndex: 'COOPMERCHANTS_STATE',
      title: '商户状态',
      align: 'center',
      width: 100,
      valueType: 'select',
      valueEnum: { 0: { text: '无效', status: 'error' }, 1: { text: '有效', status: 'success' } },
      initialValue: '1'
    },
    {
      dataIndex: 'MERCHANTS_ADDRESS',
      title: '商户地址',
      colSize: 24,
      hideInTable: true,
      hideInSearch: true,
    },
    {
      dataIndex: 'STAFF_NAME',
      title: '操作员',
      hideInSearch: true,
      hideInTable: true,
    },
    {
      dataIndex: 'OPERATE_DATE',
      title: '更新时间',
      align: 'center',
      width: 100,
      valueType: 'fromNow',
      hideInSearch: true,
    },
    {
      dataIndex: 'option',
      title: '操作',
      width: 80,
      align: 'center',
      valueType: 'option',
      hideInSearch: true,
      hideInTable: isComponent,
      render: (_, record) => {
        return (
          <a
            onClick={() => {
              console.log('record', record);
              setCurrentRow({ ...record });
              handleModalVisible(true);
            }}
          >
            编辑
          </a>
        );
      },
    },
  ];

  // 拿到详情数据
  const handleGetDetailData = async (record: any) => {
    setDetailLoading(true)
    const data = await getShopDetail({ CoopMerchantsId: record.COOPMERCHANTS_ID })
    setDetail(data)
    const options = await getFieldEnum({ FieldExplainField: 'MERCHANTS_TYPE' });
    options.forEach((item: any) => {
      if (item.value === data.MERCHANTTYPE_ID) {
        data.MERCHANTTYPE_IDNAME = item.label
      }
    })
    const contacts = await getLinkManList(Number(record.COOPMERCHANTS_ID))
    setContactsList(contacts)
    setDetailLoading(false)
  }



  useImperativeHandle(onRef, () => ({
    selectRow,
    selectRowDetail
  }));

  return (
    <PageContainer header={{
      title: '',
      breadcrumb: {},
    }}>

      <ProTable<MerchantModel>
        style={{ height: 'calc(100vh - 135px)', background: '#fff' }}
        scroll={{ y: 'calc(100vh - 410px)' }}
        rowKey="COOPMERCHANTS_ID"
        formRef={formRef}
        headerTitle={<PageTitleBox props={props} />}
        className='MerchatsTable'
        actionRef={actionRef}
        search={{ span: 6 }}
        request={async (params, sorter) => {
          // 排序字段
          const sortstr = Object.keys(sorter).map(n => {
            const value = sorter[n]
            return value ? `${n} ${value.replace('end', '')}` : ''
          })

          const data = await getList({
            ...params,
            sortstr: sortstr.length ? sortstr.toString() : "OPERATE_DATE desc",
            keyWord: params.searchKey ? { key: "COOPMERCHANTS_NAME,TAXPAYER_IDENTIFYCODE", value: params.searchKey } : null, // 关键词查询
            pagesize: params.pageSize
          });
          return data;
        }}
        columns={columns}
        toolbar={{
          actions: [
            <Button
              key="new"
              icon={<PlusOutlined />}
              type="primary"
              onClick={() => {
                handleModalVisible(true);
              }}
            >
              商户
            </Button>,
          ],
        }}
        pagination={{ defaultPageSize: 10 }}
        options={false}
        rowSelection={isComponent ? {
          type: "radio",
          onChange: (_, selectedRows) => {
            // setSelectRow
            console.log('_', _);
            console.log('selectedRows', selectedRows);
            if (selectedRows && selectedRows.length > 0) {
              setSelectRow(selectedRows[0].COOPMERCHANTS_NAME)
              setSelectRowDetail(selectedRows)
            } else {
              setSelectRow('')
              setSelectRowDetail(undefined)
            }
          }
        } : false}
      />
      <Drawer
        width={600}
        visible={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.COOPMERCHANTS_NAME && (
          <ProDescriptions<MerchantModel>
            column={2}
            title={currentRow?.COOPMERCHANTS_NAME}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.COOPMERCHANTS_ID,
            }}
            columns={columns as ProDescriptionsItemProps<MerchantModel>[]}
          />
        )}
      </Drawer>


      <AddEdit currentRow={currentRow} modalVisible={modalVisible} handleModalVisible={handleModalVisible} setCurrentRow={setCurrentRow}
        actionRef={actionRef} disabled={disabled} setDraggleDisabled={setDraggleDisabled} bounds={bounds} onDraggaleStart={onDraggaleStart}
        draggleRef={draggleRef} />



      <Drawer
        width={'560px'}
        visible={showDrawer}
        onClose={() => {
          setShowDrawer(false);
        }}
        bodyStyle={{ padding: 0 }}
        footer={
          <div style={{ width: '100%', display: 'flex', justifyContent: 'flex-end' }}>
            <Button onClick={() => { setShowDrawer(false) }}>取消</Button>
            {/* <Button type={'primary'}>确定</Button> */}
          </div>
        }
        closable={false}

      >
        {
          detailLoading ?
            <LoadingBox /> :
            <>
              {
                detail ?
                  <div className={'drawer'}>
                    <div className={'drawerTop'}>
                      <span className={'drawerTitle'}>商家信息</span>
                      <img className={'closeIcon'} src={closeIcon} onClick={() => { setShowDrawer(false) }}></img>
                    </div>
                    <div className={'drawerContent'}>
                      <div className={'drawerHeader'}>
                        <div className={'top'}>
                          <div className={'topLeft'}>
                            <div className={'image'}>
                              <img className={'headerIcon'} src={storeIcon} />
                            </div>
                            <div className={'message'}>
                              <p className={'companyName'}>{detail.COOPMERCHANTS_NAME}</p>
                              <p className={'label'}>{detail.COOPMERCHANTS_NATURE === 1000 ? '企业' : '个体'}</p>
                            </div>
                          </div>
                          <div className={'topRight'}>
                            {
                              detail.COOPMERCHANTS_STATE === 1 ?
                                <div className={'state'}>
                                  <img className={'stateIcon'} src={effective} />
                                  <span className={'stateText'}>{'有效'}</span>
                                </div>
                                : <div className={'state'}>
                                  <img className={'stateIcon'} src={wrong} />
                                  <span className={'stateText'} style={{ color: '#ccc' }}>{'无效'}</span>
                                </div>
                            }
                          </div>
                        </div>
                        <div className={'list'}>
                          <div className={'item'} style={{ alignItems: 'flex-start' }}>
                            <img className={'icon'} src={legalPerson} style={{ marginTop: '4px' }}></img>
                            <span className={'messageLabel'}>法人信息</span>
                            {
                              !detail.COOPMERCHANTS_LINKMAN && !detail.COOPMERCHANTS_TELEPHONE ? <span style={{ marginLeft: '24px' }}>-</span> :
                                <p className={'text'}><span style={{ marginRight: '12px' }}>{detail.COOPMERCHANTS_LINKMAN}</span>  {detail.COOPMERCHANTS_MOBILEPHONE}</p>
                            }
                          </div>

                          <div className={'item'} style={{ alignItems: 'flex-start' }}>
                            <img className={'icon'} src={account} style={{ marginTop: '4px' }}></img>
                            <span className={'messageLabel'}>开户信息</span>
                            {
                              !detail.BANK_NAME && !detail.BANK_ACCOUNT ? <span style={{ marginLeft: '24px' }}>-</span> :
                                <p className={'text'}><span style={{ marginRight: '12px' }}>{detail.BANK_NAME}</span> {detail.BANK_ACCOUNT}</p>
                            }
                          </div>

                          <div className={'item'}>
                            <img className={'icon'} src={code}></img>
                            <span className={'messageLabel'}>统一信用代码</span>
                            <p className={'text'}>{detail.TAXPAYER_IDENTIFYCODE || '-'}</p>
                          </div>
                        </div>
                      </div>

                      <div className={'other'}>
                        <div className={'otherItem'}>
                          <img className={'icon'} src={button} />
                          <span className={'label'}>所属类别</span>
                          <span className={'type'}>{detail.MERCHANTTYPE_IDNAME}</span>
                        </div>

                        <div className={'otherItem'} style={{ alignItems: 'flex-start' }}>
                          <img className={'icon'} src={brandDesc} style={{ marginTop: '4px' }} />
                          <span className={'label'} >商户简称</span>
                          <span className={'value'}>{detail.COOPMERCHANTS_EN || '-'}</span>
                        </div>

                        <div className={'otherItem'} style={{ alignItems: 'flex-start' }}>
                          <img className={'icon'} src={map} style={{ marginTop: '4px' }} />
                          <span className={'label'}>商户地址</span>
                          <span className={'value'}>{detail.COOPMERCHANTS_ADDRESS || '-'}</span>
                        </div>

                        <div className={'otherItem'} style={{ alignItems: 'flex-start' }}>
                          <img className={'icon'} src={phone} style={{ marginTop: '7px' }} />
                          <span className={'label'} style={{ marginTop: '4px' }}>联系人</span>
                          <div className={'list'}>
                            {
                              contactsList.length && contactsList.length > 0 ?
                                contactsList.map((item: any) => {
                                  return <div className={'listItem'}>
                                    <span className={'name'}>{item.LINKER_NAME}</span>
                                    <span className={'phone'}>{item.LINKER_MOBILEPHONE}</span>
                                    {
                                      item.LINKER_STATE === 1 ?
                                        <div className={'state'}>
                                          <img className={'icon'} src={success} />
                                          <span className={'text'}>有效</span>
                                        </div>
                                        :
                                        <div className={'state'}>
                                          <img className={'icon'} src={wrong} />
                                          <span className={'text'} style={{ color: '#ccc' }}>无效</span>
                                        </div>
                                    }
                                  </div>
                                }) : ''
                            }
                          </div>
                        </div>

                        <div className={'otherItem'} style={{ alignItems: 'flex-start' }}>
                          <img className={'icon'} src={shopIcon} style={{ marginTop: '15px' }} />
                          <span className={'label'} style={{ marginTop: '11px' }}>经营品牌</span>
                          <div className={'imgList'}>
                            {
                              detail.BrandList.length && detail.BrandList.length > 0 ?
                                detail.BrandList.map((item: any) => {
                                  return item.ico ? <img className={'imgItem'} src={item.ico} /> : ''
                                })
                                // [{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}].map((item: any)=>{
                                //   return <img className={'imgItem'} src={item.ico}/>
                                // })
                                : ''
                            }
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                  : ''
              }
            </>
        }
      </Drawer>
    </PageContainer>
  );
};

export default MerchatsTable;
