import { Form, Select, Tabs, Card, Pagination, Table, message, Button, Modal, Progress, Tag, Descriptions, Popconfirm } from 'antd';
const { TabPane } = Tabs;
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import React, { useState, useRef, useEffect } from 'react';
import { GetStoreInfos, AddPrinter, GetPrinter, UpdatePrinter, SetPrinterHost, DelPrinter, GetPrinterTemplater, GetStoreFoodMenu } from './service';
import ProList from '@ant-design/pro-list';
import { ProFormRadio } from '@ant-design/pro-form';
import Field from '@ant-design/pro-field';
import ProForm, { ProFormText, ModalForm } from '@ant-design/pro-form';
import { deDEIntl } from '@ant-design/pro-provider';
import { PlusOutlined } from '@ant-design/icons';
const PrinterInfo = () => {
  const formRef = useRef();
  const actionRef = useRef();
  const [tabDataLsit, SetTabDataLsit] = useState([]);
  const [tabTotal, SetTabTotal] = useState(0);
  const [cardActionProps, setCardActionProps] = useState('actions');
  const [state, setState] = useState('read');
  const [currentTabRow, setCurrentTabRow] = useState();
  const [currentRow, setCurrentRow] = useState({});
  // 弹框触发
  const [modalVisit, setModalVisit] = useState(false);
  const [printerTemplaterList, setPrinterTemplaterList] = useState([]);
  const [pageupdate,setpageupdate] = useState(false);
  // 打印机店铺商品
  var storeFoodMenu = [];

  useEffect(async () => {
    GetTabDataLsit(1);
    await GetPrinterTemplater().then((re) => {
      setPrinterTemplaterList(re.data);
    });
  }, [])



  useEffect(async () => {

  }, [currentTabRow]);



  const GetStoreFoodMenuList = async (val) => {
    let re = await GetStoreFoodMenu(val);
    if (re.data) {
      setpageupdate(!pageupdate)
      storeFoodMenu=re.data;
    }
  }



  const printerList = async (storeid) => {
    var list = [];
    var data = await GetPrinter(storeid).then((re) => {
      re?.data.forEach(item => {
        if (item?.id == currentRow?.id) {
          var obj = currentRow;
          obj.state = obj.state == "read" ? "edit" : "read";
          item.state = obj.state;
          setCurrentRow(obj);
        } else {
          item.state = "read";
        }
        list.push(item);
      })
    });
    return list;
  }

  const GetHtml = async (val) => {
    console.log('我要执行了');
    await GetStoreFoodMenuList(val.storeId);
    var list = [];
    let data = await printerList([val.storeId]);
    list = data?.map((item) => ({
      title: item.name,
      subTitle: item.isHost ? (<Tag color="#5BD8A6">主打印机</Tag>) : (""),
      actions: [
        <a key="run" onClick={async () => {
          await SetPrinterHost(val.storeId, item.id).then((re) => {
            if (re.data) {
              setCurrentRow({});
              actionRef.current.reloadAndRest();
              message.success('设置成功');
            } else {
              message.success('设置失败');
            }
          })
        }}  >设为主机</a>,
        <Popconfirm
          type="primary"
          key="primary"
          title="确认删除吗？"
          okText="是"
          cancelText="否"
          onConfirm={async () => {
            await DelPrinter([item.id]).then((re) => {
              if (re.data) {
                setCurrentRow({});
                actionRef.current.reloadAndRest();
                message.success('删除成功');
              } else {
                message.success('删除失败');
              }
            })
          }}
          onCancel={() => { }}
        >
          <a href="#">删除</a>
        </Popconfirm>,
        <a key="delete"
          onClick={async () => {
            actionRef.current.reloadAndRest();
            if (item.state == "edit") {
              formRef.current.submit();
            }
          }} >{item.state == "edit" ? "保存" : "编辑"}</a>],
      avatar: 'https://gw.alipayobjects.com/zos/antfincdn/UCSiy1j6jx/xingzhuang.svg',
      info: item,
      content: (
        <div style={{ flex: 1, }} >
          <div >
            <ProForm
              labelCol={{ span: 4 }}
              onFinish={async (values) => {
                var result = await UpdatePrinter(values);
                if (result.data) {
                  message.success('编辑成功');
                } else {
                  message.success('编辑失败');
                }
              }}
              formRef={formRef}
              submitter={false}
              layout={'horizontal'}
              initialValues={{
                id: item.id,
                state: item.state,
                name: item.name,
                applicationId: item.applicationId,
                applicationkey: item.applicationkey,
                terminalId: item.terminalId,
                terminalKey: item.terminalKey,
                templaterId: item.templaterId,
                goodsIdList: item.goodsIdList
              }}
              autoFocusFirstInput>

              <ProForm.Item name="id" hidden={true} >
                <Field mode={item.state} />
              </ProForm.Item>
              <ProForm.Item name="applicationId" label="应用ID" placeholder="请输入应用ID">
                <Field mode={item.state} />
              </ProForm.Item>
              <ProForm.Item style={{ marginTop: '-10px' }} name="applicationkey" label="应用秘钥s" placeholder="请输入应用秘钥">
                <Field valueType="password" mode={item.state} />
              </ProForm.Item>
              <ProForm.Item style={{ marginTop: '-10px' }} name="terminalId" label="终端IDs" placeholder="请输入终端ID">
                <Field mode={item.state} />
              </ProForm.Item>
              <ProForm.Item style={{ marginTop: '-10px' }} name="terminalKey" label="终端秘钥" placeholder="请输入终端秘钥">
                <Field valueType="password" mode={item.state} />
              </ProForm.Item>
              <ProForm.Item style={{ marginTop: '-10px' }} name="name" label="打印机名称" placeholder="请输入打印机名称" hidden={item.state != "edit" ? true : false} >
                <Field mode={item.state} />
              </ProForm.Item>
              <ProFormText
                mode={item.state}
                name="templaterId"
                label="模板"
                placeholder="模板"
                request={() => {
                  let list = [];
                  printerTemplaterList?.map((item, index) => {
                    list.push({ label: item.title, value: item.id });
                  });
                  return list;
                }}
              />
              <div style={{ overflow: 'auto', width: '430px' }}>

                <ProFormText
                  mode={item.state}
                  name="goodsIdList"
                  valueType="checkbox"
                  label="商品"

                  request={() => {
                    let store_list = [];
                    console.log('我是商品的重新组装数据22222222', storeFoodMenu);
                    storeFoodMenu.map((item, index) => {
                      store_list.push({ label: item.foodName, value: item.foodId });
                    });
                    console.log('我是商品的重新组装数据', store_list);
                    return store_list;
                  }}
                />


              </div>

            </ProForm>
          </div>
        </div>
      ),
    }));
    list.push({
      info: {},
      content: (
        <div style={{ flex: 1, }} >
          <div style={{ height: 195, textAlign: 'center' }}
            onClick={() => {
              console.log('我点击了', val);
              setModalVisit(true);
              setCurrentTabRow(val);
            }} >
            <PlusOutlined style={{ fontSize: '50px', color: '#08c', marginTop: '60px' }} />
          </div>
        </div>
      )
    });

    console.log('我这里到底是执行了多少次', list);
    return list;
  }

  const GetTabDataLsit = async (page) => {
    try {
      await GetStoreInfos({ current: page, pageSize: 10 }).then((r) => {
        SetTabTotal(r.data.total);
        SetTabDataLsit(r.data.data);
      });
    } catch {
      SetTabDataLsit(false);
    }

  }
  return (
    <PageContainer>
      <Card ></Card>
      <Card headStyle={{ border: '0px ' }} title="店铺商品" style={{ marginTop: '17px' }}>
        <Tabs defaultActiveKey="1" tabPosition="left" onChange={(key) => {
         console.log(key);
         GetStoreFoodMenuList(key);
          // 加载右边店铺信息
        }}>
          {tabDataLsit?.map((item) => {
            return (
              <TabPane tab={item.storeName} key={item.storeId}   onChange={()=>{
                console.log('11111111111111');
              }}>
                <ProList
                  actionRef={actionRef}
                  pagination={false}
                  
                  showActions="hover"
                  rowSelection={{}}
                  grid={{ gutter: 8, column: 3 }}
                  onItem={(record) => {
                    return {
                      onMouseEnter: () => {
                        setCurrentRow(record.info);
                      },
                      onClick: () => {
                        setCurrentRow(record.info);
                      },
                    };
                  }}
                  metas={{
                    title: {},
                    subTitle: {},
                    type: {},
                    avatar: {},
                    content: {},
                    actions: {
                      cardActionProps,
                    },
                  }}
                  headerTitle="打印机"
                  request={async (params) => {
                    return {
                      data: await GetHtml(item),
                      success: true,
                    };
                  }} />
              </TabPane>
            );

          })}
        </Tabs>
        <Pagination
          size='small'
          style={{ float: 'right' }}
          total={tabTotal}
          //onChange={(page, pageSize) => { getStoreInfoPageInfo(page) }}
          showTotal={(tabTotal, range) => `总共 ${tabTotal} 条`}
          defaultPageSize={10}
          defaultCurrent={1}
        />
      </Card>
      {/* 弹框 */}
      <ModalForm
        labelCol={{ span: 4 }}
        visible={modalVisit}
        modalProps={{
          onCancel: () => setModalVisit(false),
        }}
        onFinish={async (values) => {
          values.storeId = currentTabRow.storeId;
          var result = await AddPrinter(values);
          if (result.data) {
            actionRef.current.reloadAndRest();
            setModalVisit(false)
            message.success('添加成功');
          } else {
            message.success('添加失败');
          }
        }}
        formRef={formRef}
        layout={'horizontal'}
        autoFocusFirstInput>
        <ProForm.Item name="applicationId" label="应用ID" placeholder="请输入应用ID">
          <Field mode={'edit'} />
        </ProForm.Item>
        <ProForm.Item style={{ marginTop: '-10px' }} name="applicationkey" label="应用秘钥" placeholder="请输入应用秘钥">
          <Field valueType="password" mode={'edit'} />
        </ProForm.Item>
        <ProForm.Item style={{ marginTop: '-10px' }} name="terminalId" label="终端ID" placeholder="终端ID">
          <Field mode={'edit'} />
        </ProForm.Item>
        <ProForm.Item style={{ marginTop: '-10px' }} name="terminalKey" label="终端秘钥" placeholder="终端秘钥">
          <Field valueType="password" mode={'edit'} />
        </ProForm.Item>
        <ProForm.Item style={{ marginTop: '-10px' }} name="name" label="打印机名称" placeholder="请输入打印机名称" >
          <Field mode={'edit'} />
        </ProForm.Item>

        <ProFormText
          mode={'edit'}
          name="templaterId"
          label="模板"
          placeholder="模板"
          request={() => {
            var list = [];
            printerTemplaterList?.map((item, index) => {
              list.push({ label: item.title, value: item.id });
            });
            return list;
          }}
        />

        <ProFormText
          mode={'edit'}
          name="goodsIdList"
          valueType="checkbox"
          label="商品"
          placeholder="商品"
          request={() => {
            var list = [];
            storeFoodMenu?.map((item, index) => {
              list.push({ label: item.foodName, value: item.foodId });
            });
            console.log('我是重新组装的数据', list);
            return list;

          }}
        />
      </ModalForm>
    </PageContainer>
  );
};

export default PrinterInfo;
