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 actionRef = useRef();
  const formRef = useRef();
  const [cardActionProps, setCardActionProps] = useState('actions');
  const [storeInfoList, setStoreInfoList] = useState([]);
  const [tabTotal, SetTabTotal] = useState(0);
  const [printerHtml, SetPrinterHtml] = useState([]);
  const [currentPrinter, setCurrentPrinter] = useState({});
  const [currentStoreid, setCurrentStoreid] = useState("");
  const [storeFoodMenuAll, setStoreFoodMenuAll] = useState([]);
  const [modalVisit, setModalVisit] = useState(false);
  const [printerTemplaterList, setPrinterTemplaterList] = useState([]);

  // 打印机店铺商品

  useEffect(async () => {
    GetStoreInfoList(1);
    //获取模板
    GetPrinterTemplater().then((re) => {
      setPrinterTemplaterList(re.data);
    });
  }, [])





  //获取店铺
  const GetStoreInfoList = async (page) => {
    try {
      await GetStoreInfos({ current: page, pageSize: 10 }).then((r) => {
        SetTabTotal(r.data.total);
        console.log('我是店铺信息', r.data.data);
        setStoreInfoList(r.data.data);
      });
    } catch {
      setStoreInfoList([]);
    }
  }

  //获取打印机
  const GetprinterList = async (storeid) => {
    var list = [];
    var data = await GetPrinter(storeid).then((re) => {
      re?.data.forEach(item => {
        if (item.id == currentPrinter?.id) {
          var obj = currentPrinter;
          obj.state = obj.state == "read" ? "edit" : "read";
          item.state = obj.state;
          setCurrentPrinter(obj);
        } else {
          item.state = "read";
        }
        list.push(item);
      })
    });
    return list;
  }




  ///获取店铺的打印机（Html）
  const GetHtml = async (key) => {
    // debugger


    //打印机
    var printerList = await GetprinterList(key);
    //商品信息
    let storeFoodMenuList = await GetStoreFoodMenu(key);
    setStoreFoodMenuAll(storeFoodMenuList.data);

    const printerListHtml = printerList?.map((item) => ({
      title: item.name,
      subTitle: item.isHost ? (<Tag color="#5BD8A6">主打印机</Tag>) : (""),
      actions: [
        <a key="run" onClick={async () => {
          await SetPrinterHost(key, item.id).then((re) => {
            if (re.data) {
              actionRef.current.reload();
              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) {
                actionRef.current.reload();
                message.success('删除成功');
              } else {
                message.success('删除失败');
              }
            })
          }}
          onCancel={() => { }} >
          <a href="#">删除</a>
        </Popconfirm>,
        <a key="delete"
          onClick={async () => {
            actionRef.current.reload();
            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, width: '100%' }} >
          <div style={{ overflow: 'auto', height: '555px', float: 'left', width: '100%' }}>
            <ProForm
              labelCol={{ span: 5 }}
              style={{ float: 'left', width: '80%', margin: '10px' }}
              onFinish={async (values) => {
                var result = await UpdatePrinter(values);
                if (result.data) {
                  actionRef.current.reload();
                  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="应用秘钥" placeholder="请输入应用秘钥">
                <Field valueType="password" mode={item.state} />
              </ProForm.Item>
              <ProForm.Item style={{ marginTop: '-10px' }} name="terminalId" label="终端ID" 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: '100%', float: 'left', textAlign: 'left', margin: '5px', padding: '5px' }}>
                <ProFormText
                  mode={item.state}
                  name="goodsIdList"
                  valueType="checkbox"
                  label="商品"
                  request={() => {
                    let list = [];
                    storeFoodMenuList?.data.map((item, index) => {
                      list.push({ label: item.foodName, value: item.foodId });
                    });
                    return list;
                  }}
                />
              </div>
            </ProForm>
          </div>
        </div>
      ),
    }));

    printerListHtml.push({
      info: {},
      content: (
        <div style={{ flex: 1, }} >
          <div style={{ height: 195, textAlign: 'center' }}
            onClick={() => {
              setModalVisit(true);
              setCurrentStoreid(key);
            }} >
            <PlusOutlined style={{ fontSize: '50px', color: '#08c', marginTop: '60px' }} />
          </div>
        </div>
      )
    });
    return printerListHtml;
  }


  return (
    <PageContainer>
      <Card ></Card>
      <Card headStyle={{ border: '0px ' }} title="店铺打印机" style={{ marginTop: '17px' }}>
        <Tabs defaultActiveKey="1" tabPosition="left" onChange={async (key) => { }}>
          {storeInfoList?.map((item) => (

            <TabPane tab={item.storeName} key={item.storeId}>

              <ProList
                params={{ 'storeid': item.storeId }}
                actionRef={actionRef}
                pagination={false}
                showActions="hover"
                rowSelection={{}}
                grid={{ gutter: 8, column: 3 }}
                onItem={(record) => {
                  return {
                    onMouseEnter: () => {
                      setCurrentPrinter(record.info);
                    },
                    onClick: () => {
                      setCurrentPrinter(record.info);
                    },
                  };
                }}
                metas={{ title: {}, subTitle: {}, type: {}, avatar: {}, content: {}, actions: { cardActionProps, }, }}
                headerTitle="打印机"

                request={async (params) => {
                  return {
                    data: await GetHtml(params.storeid),
                    success: true,
                  };
                }}
              />
            </TabPane>
          ))}


        </Tabs>
      </Card>
      {/* 弹框 */}
      <ModalForm
        labelCol={{ span: 4 }}
        visible={modalVisit}
        modalProps={{
          onCancel: () => setModalVisit(false),
        }}
        onFinish={async (values) => {
          values.storeId = currentStoreid;
          var result = await AddPrinter(values);
          if (result.data) {
            actionRef.current.reload();
            setModalVisit(false)
            message.success('添加成功');
          } else {
            message.success('添加失败');
          }
        }}
        formRef={formRef}
        layout={'horizontal'}
        autoFocusFirstInput>
        <div style={{ width:'98%' }} >
          <ProFormText style={{ marginTop: '-10px', }} name="applicationId" label="应用ID" placeholder="请输入应用ID">
            <Field mode={'edit'} />
          </ProFormText>
          <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="模板"
            style={{ marginTop: '-10px' }}
            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 = [];
              storeFoodMenuAll?.map((item, index) => {
                list.push({ label: item.foodName, value: item.foodId });
              });
              return list;

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

export default PrinterInfo;
