import { PlusOutlined } from '@ant-design/icons';
import { Button, message, Input, Drawer, Popconfirm, Checkbox } 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 { history } from 'umi';
import {
  goods,
  updateGoods,
  goodsType,
} from './service';
import moment from 'moment';

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

const handleUpdate = async (fields) => {
  console.log("fields",fields);
  const hide = message.loading('正在设置可预订数量');
  try {
    await updateGoods({
      goodsId: fields.id,
      qty: fields.qty,
      mealType: fields.mealType,
      startReserveTime: fields.startReserveTime,
      endReserveTime: fields.endReserveTime
    }).then((r) => {
      if (r.data) {
        message.success('设置可预订数量成功');
      } else {
        message.error('设置可预订数量失败请重试！');
      }
    });
    return true;
  } catch (error) {
    hide();

    return false;
  }
};

const GoodsManage = () => {
  const [goodsTypes, setGoodsTypes] = useState([]);

  /** 新建/更新窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState(false);
  /** 分布更新窗口的弹窗 */
  const actionRef = useRef();
  const [currentRow, setCurrentRow] = useState();
  const [selectedRowsState, setSelectedRows] = useState([]);
  /** 国际化配置 */

  useEffect(() => {
    function initGoodsType() {
      goodsType({ current: 1, pageSize: 1000 }).then((r) => {
        var arr = r.data.data;
        arr.forEach((element) => {
          element.text = element.goodsType_Name;
          element.goodsTypeId = element.id;
        });
        setGoodsTypes(arr);
      });
    }
    initGoodsType();
  }, []);
  const columns = [
    {
      title: '主键',
      dataIndex: 'id',
      hideInTable: true,
      hideInSearch: true,

    },
    {
      title: '图片地址',
      dataIndex: 'imgUrl',
      hideInTable: true,
      hideInSearch: true,
    },
    {
      title: '编码',
      dataIndex: 'code',
      valueType: 'textarea',
    },
    {
      title: '名称',
      dataIndex: 'name',
      valueType: 'textarea',
    },
    {
      title: '基础价格',
      dataIndex: 'price',
      hideInForm: true,
      renderText: (val) => `${val}¥`,
      hideInSearch: true,
    },
    {
      title: '会员价',
      dataIndex: 'vipPrice',
      hideInForm: true,
      renderText: (val) => `${val}¥`,
      hideInSearch: true,
    },
    {
      title: '商品小类',
      dataIndex: 'goodsTypeName',
      hideInForm: true,
      hideInSearch: true,
      // valueEnum: goodsTypes
    },
    {
      title: '商品类型',
      dataIndex: 'goodsTypeId',
      hideInForm: true,
      hideInTable: true,
      // hideInSearch: true,
      valueEnum: goodsTypes,
    },
    {
      title: '可预订数量',
      dataIndex: 'qty',
    },
    {
      title: '可预定时段',
      dataIndex: 'mealType',
      render: (_, record) => {
        var mealtypes = "";
        if (record.mealType) {
          var str_array = record.mealType.split(',')

          for (var i = 0; i < str_array.length; i++) {
            if (str_array[i] === '1')
              mealtypes += "[早餐]";
            if (str_array[i] === '2')
              mealtypes += "[午餐]";
            if (str_array[i] === '3')
              mealtypes += "[晚餐]";
          }
        }
        return mealtypes;
      }

    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="primary"
          type="primary"
          onClick={() => {
            handleModalVisible(true);
            const temp = JSON.parse(JSON.stringify(record));
            if (temp.startReserveTime) { temp.startReserveTime =  temp.startReserveTime = moment(temp.startReserveTime); }
            else {temp.startReserveTime =  moment(moment(new Date(Date.now() + 24 * 60 * 60 * 1000)).format('YYYY-MM-DD 00:00:00'));}
            if (temp.endReserveTime) { temp.endReserveTime = moment(temp.endReserveTime); }
            else { temp.endReserveTime =  moment(moment(new Date(Date.now() + 24 * 60 * 60 * 1000)).format('YYYY-MM-DD 23:59:59')); }
            setCurrentRow(temp);
          }}
        >
          设置可预定数量
        </a>
      ],
    },
  ];
  return (
    <PageContainer>
      <ProTable
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        request={async (params) => {
          var goodsData = [];
          if (params.goodsTypeId != undefined) {
            params.goodsTypeId = goodsTypes[params.goodsTypeId].goodsTypeId;
          }
          var total = 0;
          await goods(params).then((r) => {
            goodsData = r.data.data;
            // goodsData.forEach((x) => {
            //   x.status = x.status.toString();
            // });
            total = r.data.total;
          });
          return {
            data: goodsData,
            success: true,
            total: total,
          };
        }}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      <CreateForm
        onFinish={async (value) => {
          var success = false;

          if (typeof value.mealType === 'object') {
            value.mealType = value.mealType.join();
          }
          // value.mealType = value.mealType.join();
          console.log("调试", value);
          value.startReserveTime = new Date(value.startReserveTime).toLocaleString();
          value.endReserveTime = new Date(value.endReserveTime).toLocaleString();
          success = await handleUpdate(value);
          if (success) {
            handleModalVisible(false);
            setCurrentRow(undefined);

            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
          actionRef.current.reload();
        }}
        onCancel={() => {
          handleModalVisible(false);
          setCurrentRow(undefined);
        }}
        createModalVisible={createModalVisible}
        values={currentRow || {}}
      />
    </PageContainer>
  );
};

export default GoodsManage;
