import { PlusOutlined } from '@ant-design/icons';
import { Modal, Button, message, Input, Drawer, TreeSelect } 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 QRCode from 'qrcode.react';
import CreateForm from './components/CreateForm';
import GoodsTableList from '../storeGoods';
import StoreBatchingStockTable from '../storeBatchingStock';
import {
  GetStoreInfoPageAsync,
  AddStoreInfoAsync,
  UpdateStoreInfofoAsync,
  DelStoreInfoAsync,
  UpdateStoreStatusAsync,
  GetDicList,
} from './services';
import { GetStoreTypePageAsync } from '../storeType/services';
import { GetStoreLevelPageAsync } from '../storeLevel/services';
import { gettree } from '../../sys/org/service';
const key = 'message';

//添加
const handleAdd = async (fields) => {
  try {
    message.loading('正在添加', key);
    await AddStoreInfoAsync(JSON.stringify(fields)).then((r) => {
      message.destroy(key);
      if (r.data) {
        message.success('添加成功');
        return true;
      } else {
        message.error('添加失败');
        return false;
      }
    });
  } catch (error) {
    message.error('添加失败请重试！');
    return false;
  }
};
//修改
const handleUpdate = async (fields) => {
  try {
    message.loading('正在修改', key);
    message.destroy(key);
    await UpdateStoreInfofoAsync(JSON.stringify(fields)).then((r) => {
      message.destroy(key);
      if (r.data) {
        message.success('修改成功');
        return true;
      } else {
        message.success('修改失败');
        return false;
      }
    });
  } catch (error) {
    message.error('修改失败请重试！');
    return false;
  }
};

//删除
const handleRemove = async (selectedRows) => {
  try {
    message.loading('正在删除');
    let ids = [];
    selectedRows.forEach((item) => {
      ids.push(item.id);
    });
    await DelStoreInfoAsync(ids).then((r) => {
      if (r.data) {
        message.success('删除成功');
        return true;
      } else {
        message.success('删除失败');
        return false;
      }
    });
  } catch (error) {
    message.error('删除失败请重试！');
    return false;
  }
};

const GoodsTypeManage = () => {
  const [storeLevel, setStoreLevel] = useState();
  const [storeType, setStoreType] = useState();

  const [storeLevelArray, setStoreLevelArray] = useState([]);
  const [storeTypeArray, setStoreTypeArray] = useState([]);
  const [OrgList, setOrgList] = useState([]);
  const [OrgListArray, setOrgListArray] = useState([]);
  const [dicDataAny, setDicDataAny] = useState([]);
  const [dicData, setDicData] = useState([]);
  //初始化数据
  useEffect(() => {
    const initStoreType = () => {
      GetStoreTypePageAsync({ current: 1, pageSize: 1000 }).then((data) => {
        let list = {};
        let list2 = [];
        data.data.data.forEach((item) => {
          list2.push({
            text: item.storeType_Name,
            id: item.id,
          });
          list[item.id] = { text: item.storeType_Name };
        });
        console.log(list);
        setStoreTypeArray(list2);
        setStoreType(list);
      });
    };
    const initStoreLevel = (val) => {
      var data = GetStoreLevelPageAsync({ current: 1, pageSize: 1000 }).then((data) => {
        var list = {};
        let list2 = [];
        data.data.data.forEach((item) => {
          list2.push({
            text: item.storeLevel_Name,
            id: item.id,
          });
          list[item.id] = { text: item.storeLevel_Name };
        });
        setStoreLevel(list);
        setStoreLevelArray(list2);
      });
    };
    function initOrgList() {
      gettree().then((r) => {
        setOrgList(r.data);
        let list = {};
        formateData(r.data);
        function formateData(datas) {
          for (var i in datas) {
            list[datas[i]['value']] = { text: datas[i]['title'] };
            if (datas[i].children) {
              formateData(datas[i].children);
            }
          }
        }
        setOrgListArray(list);
      });
    }
    initOrgList();
    initStoreType();
    initStoreLevel();
    function intDicData() {
      GetDicList('DeviceClientType').then((r) => {
        var arr = r.data;
        let data = {};
        if (r.succeeded) {
          var list = [];
          arr.forEach((item) => {
            data[item.code] = { text: item.remark };
            list.push({
              batchingType: item.code,
              text: item.remark,
              value: item.code,
              label: item.remark,
            });
          });
          setDicDataAny(data);
          setDicData(list);
        }
      });
    }
    intDicData();
  }, []);

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

  const [storeGoodsModalVisible, setStoreGoodsModalVisible] = useState(false);

  //库存调拨
  const [stockModalVisible, setStockModalVisible] = useState(false);

  const [showDetail, setShowDetail] = useState(false);

  const actionRef = useRef();
  const [currentRow, setCurrentRow] = useState();
  const [selectedRowsState, setSelectedRows] = useState([]);
  /** 国际化配置 */
  const handleCancel = () => {
    setStoreGoodsModalVisible(false);
  };

  const columns = [
    {
      title: '主键',
      dataIndex: 'id',
      hideInSearch: true,
      hideInTable: true,
      tip: '规则名称是唯一的 key',
    },
    {
      title: '店铺名称',
      dataIndex: 'store_Name',
      valueType: 'textarea',
    },
    {
      title: '联系电话',
      dataIndex: 'store_Tel',
      valueType: 'textarea',
    },
    {
      title: '店铺地址',
      dataIndex: 'store_Addr',
      search: false,
      valueType: 'textarea',
    },
    {
      title: '图标',
      dataIndex: 'store_ImgUrl',
      search: false,
      valueType: 'textarea',
    },

    {
      title: '店铺类型',
      dataIndex: 'store_TypeId',
      valueEnum: storeType,
    },
    {
      title: '归属机构',
      dataIndex: 'orgId',
      search: false,
      valueEnum: OrgListArray,
    },
    {
      title: '店铺等级',
      dataIndex: 'store_LevelId',
      search: false,
      valueEnum: storeLevel,
    },

    {
      title: '坐标',
      dataIndex: 'store_Loc',
      valueType: 'textarea',
      search: false,
    },
    {
      title: '负责人',
      dataIndex: 'store_Cadre',
      valueType: 'textarea',
      search: false,
    },
    {
      title: '状态',
      dataIndex: 'store_Status',
      valueEnum: {
        0: { text: '正常', status: 'Processing' },
        1: { text: '停用', status: 'Success' },
      },
    },
    // {
    //   title: '创建时间',
    //   dataIndex: 'createAt',
    //   hideInForm: true,
    //   search: false,
    // },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="primary"
          onClick={() => {
            handleModalVisible(true);
            setCurrentRow(record);
          }}
        >
          {' '}
          更新
        </a>,
        <a
          key="primary"
          onClick={() => {
            record.store_Status = record.store_Status == 0 ? 1 : 0;
            UpdateStoreStatusAsync(record).then((r) => {
              if (r.data) {
                actionRef.current.reload();
              }
            });
          }}
        >
          {' '}
          {record.store_Status == 0 ? '停用' : '正常'}
        </a>,
        <a
          key="primary"
          onClick={() => {
            setCurrentRow(record);
            setStoreGoodsModalVisible(true);
          }}
        >
          {' '}
          商品上架
        </a>,
        <a
          key="primary"
          onClick={() => {
            setCurrentRow(record);
            setStockModalVisible(true);
          }}
        >
          {' '}
          库存调拨
        </a>,
        <a
          key="primary"
          onClick={() => {
            const config = {
              title: '店铺二维码',
              content: (
                <QRCode
                  id="qrCode"
                  value={`https://black-pa.com:5443/lead?StoreId=${record.id}&StoreType=`}
                  size={200} // 二维码的大小
                  fgColor="#000000" // 二维码的颜色
                  style={{ margin: 'auto' }}
                />
              ),
            };
            Modal.info(config);
          }}
        >
          {' '}
          店铺二维码
        </a>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable
        headerTitle="店铺类型"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        scroll={{ x: 2000 }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={async (params) => {
          var data = [];
          var total = 0;
          await GetStoreInfoPageAsync(params).then((r) => {
            data = r.data.data;
            total = r.data.total;
          });
          return {
            data: data,
            success: true,
            total: total,
          };
        }}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项 &nbsp;&nbsp;
              {/* <span>
                服务调用次数总计 {selectedRowsState.reduce((pre, item) => pre + item.id, 0)} 万
              </span> */}
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            删除
          </Button>
          {/* <Button type="primary">批量审批</Button> */}
        </FooterToolbar>
      )}

      <CreateForm
        storeLevel={storeLevelArray}
        storeType={storeTypeArray}
        OrgData={OrgList}
        dicData={dicData}
        onFinish={async (value) => {
          var success = false;
          if (value.id) {
            success = handleUpdate(value);
          } else {
            success = handleAdd(value);
          }
          if (success) {
            handleModalVisible(false);
            setCurrentRow(undefined);
            actionRef.current.reload();
          }
        }}
        onCancel={() => {
          handleModalVisible(false);
          setCurrentRow(undefined);
        }}
        createModalVisible={createModalVisible}
        values={currentRow || {}}
      />

      {/* 商品上架 */}
      <GoodsTableList
        onCancel={() => {
          setStoreGoodsModalVisible(false);
          setCurrentRow({});
        }}
        storeGoodsModalVisible={storeGoodsModalVisible}
        values={currentRow}
      />

      {/* 库存调拨 */}
      <StoreBatchingStockTable
        onCancel={() => {
          setStockModalVisible(false);
          setCurrentRow({});
        }}
        stockModalVisible={stockModalVisible}
        values={currentRow}
      />
    </PageContainer>
  );
};

export default GoodsTypeManage;
