import { DropboxOutlined, PlusOutlined } from '@ant-design/icons';
import { Button, message, Input, Drawer, Modal, Popconfirm } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import CreateForm from './components/CreateForm';
import {
  getAccountList,
  addAccount,
  updateAccount,
  removeAccount,
  GetStoreInfoPageAsync,
  GetBusinessAsync,
  gettree
} from './services';
import { getPlanList } from '../plan/services';

//页面 相当于 class
const AccountDetailsManage = () => {
  const [planEnum, setPlanEnum] = useState();
  const [planArray, setPlanArray] = useState([]);

  const [storeEnum, setStoreEnum] = useState();
  const [storeArray, setStoreArray] = useState([]);
  const [OrgList, setOrgList] = useState([]);
  const [OrgListArray, setOrgListArray] = useState([]);

  //初始化数据
  useEffect(() => {
    //初始化方案
    const initPlan = (val) => {
      var data = getPlanList({ current: 1, pageSize: 1000 }).then((data) => {
        var list = {};
        let list2 = [];
        data.data.data.forEach((item) => {
          list2.push({
            text: item.planName,
            id: item.id,
          });
          list[item.id] = { text: item.planName };
        });

        setPlanArray(list2);
        setPlanEnum(list);
      });
    };

    //初始化店铺
    const initStore = (val) => {
      var data = GetStoreInfoPageAsync({ current: 1, pageSize: 1000 }).then((data) => {
        var list = {};
        let list2 = [];
        data.data.data.forEach((item) => {
          list2.push({
            text: item.store_Name,
            id: item.id,
          });
          list[item.id] = { text: item.store_Name };
        });
        setStoreArray(list2);
        setStoreEnum(list);
      });
    };
    function initOrgList() {
      gettree().then((r) => {
        inittree(r.data);
        function inittree(datas) {
          for (var i in datas) {
            if(  datas[i]['type']==2||  datas[i]['type']==3){
              datas[i]['disabled']=false;
            }else{
              datas[i]['disabled']=true;
            }
          
            if (datas[i].children) {
              inittree(datas[i].children);
            }
          }
        }
        setOrgList(r.data);
        let list = {};
        formateData(r.data);
        function formateData(datas) {
          for (var i in datas) {
            list[datas[i]['disabled']]=true;
            list[datas[i]['value']] = { text: datas[i]['title'] };
            if (datas[i].children) {
              formateData(datas[i].children);
            }
          }
        }
        setOrgListArray(list);
      });
    }
    initOrgList();

    initPlan();
    initStore();
  }, []);

  /** 新建/更新窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState(false);
  /** 分布更新窗口的弹窗 */

  const [showDetail, setShowDetail] = useState(false);
  //绑定
  const actionRef = useRef();
  const [currentRow, setCurrentRow] = useState();

  //选中的行
  const [selectedRowsState, setSelectedRows] = useState([]);

  /**
   * 添加节点
   *
   * @param fields
   */
  function handleAdd(fields) {
    // message.loading('正在添加');
    try {
      addAccount(JSON.stringify(fields));
      message.success('添加成功');
      //刷新数据
      actionRef.current.reload();
      return true;
    } catch (error) {
      message.error('添加失败请重试！');
      return false;
    }
  }

  /**
   * 更新节点
   *
   * @param fields
   */

  function handleUpdate(fields) {
    try {
      updateAccount(JSON.stringify(fields)).then((r) => {
        if (r.data) {
          message.success('修改成功');
          actionRef.current.reload();
        } else {
          message.error('修改失败请重试！');
        }
      });
      return true;
    } catch (error) {
      message.error('修改失败请重试！');
      return false;
    }
  }

  /**
   * 批量删除节点
   *
   * @param selectedRows
   */
  function handleRemove() {
    try {
      removeAccount(selectedRowsState.map((item, index) => item.id)).then((r) => {
        if (r.data) {
          message.success('删除成功，即将刷新');
        } else {
          message.error('删除失败，请重试');
        }
      });
      //刷新数据
      actionRef.current.reload();
      return true;
    } catch (error) {
      message.error('删除失败，请重试');
    }
  }
  /**
   * 删除单条数据
   *
   * @param selectedRows
   */
  function handleRemoveSingle(value) {
    try {
      removeSingleAccount(value).then((r) => {
        if (r.data) {
          message.success('删除成功，即将刷新');
          //刷新数据
          actionRef.current.reload();
        } else {
          message.error('删除失败，请重试');
        }
      });
      return true;
    } catch (error) {
      message.error('删除失败，请重试');
    }
  }

  /** 国际化配置 */

  const columns = [
    {
      title: '主键',
      dataIndex: 'id',
      tip: '规则名称是唯一的 key',
      hideInSearch: true,
      hideInTable: true,
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              setCurrentRow(entity);
              setShowDetail(true);
            }}
          >
            {dom}
          </a>
        );
      },
    },
    {
      title: '店铺',
      dataIndex: 'storeId',
      valueEnum: storeEnum,
    },
    // {
    //   title: '分账账户类别',
    //   dataIndex: 'splitType',
    //   valueEnum: {
    //     0: { text: '商户' },
    //     1: { text: '个人' },
    //   },
    // },
    // {
    //   title: '分账账户名称',
    //   dataIndex: 'businessName',
    //   valueType: 'textarea',
    // },
    // {
    //   title: '分账账户号',
    //   dataIndex: 'businessId',
    //   valueType: 'textarea',
    // },
    {
      title: '分账方案',
      dataIndex: 'planId',
      valueEnum: planEnum,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      valueType: 'textarea',
      hideInSearch: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createAt',
      valueType: 'dateTime',
      hideInSearch: true,
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        const state = form.getFieldValue('state');

        if (`${state}` === '0') {
          return false;
        }

        if (`${state}` === '3') {
          return <Input {...rest} placeholder="请输入异常原因！" />;
        }

        return defaultRender(item);
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="config"
          onClick={() => {

            GetBusinessAsync(record.storeId, record.planId).then((r) => {
               if (r.data) {
                handleModalVisible(true);
                setCurrentRow(() => {
                  record.businessList = r.data;
                  return record;
                });
              }
            });
          }}
        >
          更新
        </a>,
        // <Popconfirm
        //     type="primary"
        //     key="primary"
        //     title="确认删除吗？"
        //     okText="是"
        //     cancelText="否"
        //     onConfirm={() => {
        //         handleRemoveSingle(record.id);
        //     }}
        //     onCancel={() => { }}
        // >
        //     <a href="#">删除</a>
        // </Popconfirm>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable
        headerTitle="分账账户"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        columns={columns}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalVisible(true);
              setCurrentRow({});
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        //数据绑定
        request={async (params) => {
          var franchiessSrdtypeData = [];
          var total = 0;
          await getAccountList(params).then((r) => {
            franchiessSrdtypeData = r.data.data;
            total = r.data.total;
          });
          return {
            data: franchiessSrdtypeData,
            success: true,
            total: total,
          };
        }}
        // 每行选择点击事件
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      ></ProTable>
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项 &nbsp;&nbsp;
            </div>
          }
        >
          {/* <Button
            onClick={() => {
              handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
            type="primary"
            key="primary"
          >
            批量删除
          </Button> */}

          <Popconfirm
            type="primary"
            key="primary"
            title="确认是否删除选中项？"
            okText="是"
            cancelText="否"
            onConfirm={() => {
              handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
            onCancel={() => { }}
          >
            <a href="#">批量删除</a>
          </Popconfirm>

        </FooterToolbar>
      )}
      {/* 分账账户管理(新增，修改) */}
      <CreateForm
        OrgData={OrgList}
        planArray={planArray}
        storeArray={storeArray}
        onFinish={async (value) => {

          var success = false;
          if (value.id) {
            success = await handleUpdate(value);
          } else {
            success = await handleAdd(value);
          }
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          setCurrentRow(undefined);
          handleModalVisible(false);
        }}
        createModalVisible={createModalVisible}
        values={currentRow || {}}
      />
      <Drawer
        width={600}
        visible={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.name && (
          <ProDescriptions
            column={2}
            title={currentRow?.name}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.name,
            }}
            columns={columns}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default AccountDetailsManage;
