import { FontColorsOutlined, PlusOutlined, DownOutlined, CheckOutlined, CloseOutlined } from '@ant-design/icons';
import { Modal, Form, Input, Button, Select, Popconfirm, Space, Checkbox, Col, Row, DatePicker, Card, List, Tree, message, Drawer, Divider, Tag, Tabs } 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 moment from 'moment';
const { TabPane } = Tabs;
import {
  addPracticeType,
  getPracticeType,
  editPracticeType,
  editPracticeRecord,
  addPracticeRecord,
  getPracticeRecord,
  getPracticeRelevance,
  addPracticeRelevance,
  editPracticeRelevance,
  GetAllType,
  GetAllSmallType,
  GetAllGoods,
  GetAllPractice,
  DeleteGoodsPractice
} from './service';

import CreateRelevanceForm from './components/createRelevanceForm';
import CreatetypeRelevanceForm from './components/createtypeRelevanceForm';
const PageIndex = (props) => {
  const actionRef = useRef();
  const [createtypeRelevanceModalVisible, handletypeRelevanceModalVisible] = useState();
  const [createRelevanceModalVisible, handleRelevanceModalVisible] = useState();
  const [TypecurrentRow, setTypecurrentRow] = useState();
  const [RecordCurrentRow, setRecordCurrentRow] = useState();
  const [RelevanceCurrentRow, setRelevanceCurrentRow] = useState();

  const [AllTypeList, setAllTypeList] = useState([]);

  const [Support, setSupport] = useState({
    allType: [],
    allSmallType: [],
    allGoods: [],
    allPractice: []
  });


  /**
* 数据操作
*/
  function handleRelevanceAdd(fields) {
    try {
      addPracticeRelevance(fields)
        .then((r) => {
          if (r.data) {
            message.success('添加成功');
            //刷新数据
          } else {
            message.error('添加失败请重试！');
          }
        });
      return true;
    } catch (error) {
      message.error('添加失败请重试！');
      return false;
    }
  }
  function handletypeRelevanceAdd(fields) {
    try {
      addPracticeRelevance(fields)
        .then((r) => {
          if (r.data) {
            message.success('添加成功');
          } else {
            message.error('添加失败请重试！');
          }
        });
      return true;
    } catch (error) {
      message.error('添加失败请重试！');
      return false;
    }
  }


  const handleRemove = async (id) => {
    const hide = message.loading('正在删除');
    if (!id) return true;
    try {
      await DeleteGoodsPractice({ id: id }).then((r) => {
        hide();
        if (r.data) {
          message.success('删除成功，即将刷新');
        } else {
          message.error('删除失败，请重试');
        }
      });
      return true;
    } catch (error) {
      hide();
      message.error('删除失败，请重试');
      return false;
    }
  };
  /**
   * 更新节点
   *
   * @param fields
   */

  function handleRelevanceUpdate(fields) {
    try {
      editPracticeRelevance(fields)
        .then((r) => {
          if (r.data) {
            message.success('配置成功');
          } else {
            message.error('配置失败请重试！');
          }
          setTypecurrentRow(undefined);
          //刷新数据
          actionRef.current.reload();
        });
      return true;
    } catch (error) {
      message.error('配置失败请重试！');
      return false;
    }
  }
  function handletypeRelevanceUpdate(fields) {
    try {
      //
      editPracticeRelevance(fields)
        .then((r) => {
          if (r.data) {
            message.success('配置成功');
          } else {
            message.error('配置失败请重试！');
          }
          setTypecurrentRow(undefined);
        });
      return true;
    } catch (error) {
      message.error('配置失败请重试！');
      return false;
    }
  }


  useEffect(() => {
    const parmar = {
      current: 1,
      pagesize: 99999
    };
    GetAllType(parmar).then((r) => {
      Support.allType = r.data.data;
    });
    GetAllSmallType(parmar).then((r) => {
      Support.allSmallType = r.data.data;
    });
    GetAllGoods(parmar).then((r) => {
      Support.allGoods = r.data.data;
    });
    GetAllPractice(parmar).then((r) => {
      Support.allPractice = r.data.data;
    });
    getPracticeType(parmar).then((r) => {
      setAllTypeList(r.data.data);
    });

  }, []);


  /**
   * 出品做法关联设置
   */
  const TyperelevanceColumns = [
    {
      title: '规则id',
      dataIndex: 'id',
      tip: '规则名称是唯一的 key',
      hideInSearch: true,
      hideInTable: true,
    },
    {
      title: '商品类别',
      dataIndex: 'goodsTypeName',
    },
    {
      title: '做法类别',
      dataIndex: 'makeTypeName',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="primary"
          onClick={() => {
            handletypeRelevanceModalVisible(true);
            setRelevanceCurrentRow(record);
          }}
        >
          {' '}
          修改
        </a>,
        <Popconfirm
          type="primary"
          key="primary"
          title="确认删除吗？"
          okText="是"
          cancelText="否"
          onConfirm={() => {
            handleRemove(record.id);
            actionRef.current?.reloadAndRest();
          }}
          onCancel={() => { }}
        >
          <a href="#">删除</a>
        </Popconfirm>,

      ],
    },
  ];
  const GoodsrelevanceColumns = [
    {
      title: '规则id',
      dataIndex: 'id',
      tip: '规则名称是唯一的 key',
      hideInSearch: true,
      hideInTable: true,
    },
    {
      title: '商品',
      dataIndex: 'goodsName',
    },
    {
      title: '做法',
      dataIndex: 'makeName',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="primary"
          onClick={() => {
            handleRelevanceModalVisible(true);
            setRelevanceCurrentRow(record);
          }}
        >
          {' '}
          修改
        </a>,
        <Popconfirm
          type="primary"
          key="primary"
          title="确认删除吗？"
          okText="是"
          cancelText="否"
          onConfirm={() => {
            handleRemove(record.id);
            actionRef.current?.reloadAndRest();
          }}
          onCancel={() => { }}
        >
          <a href="#">删除</a>
        </Popconfirm>,

      ],
    },
  ];

  return (
    <Tabs defaultActiveKey="1" >

      <CreateRelevanceForm
        onFinish={async (value) => {
          value.relevanceType = 2;
          var success = false;
          if (value.id) {
            success = handleRelevanceUpdate(value);
          } else {
            success = handleRelevanceAdd(value);
          }
          if (success) {
            handleRelevanceModalVisible(false);
            setRelevanceCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          setRelevanceCurrentRow(undefined);
          handleRelevanceModalVisible(false);
          actionRef.current.reload();
        }}
        Support={Support}
        createModalVisible={createRelevanceModalVisible}
        values={RelevanceCurrentRow || {}}
      >
      </CreateRelevanceForm>
      <CreatetypeRelevanceForm
        onFinish={async (value) => {
          value.relevanceType = 1;
          var success = false;
          if (value.id) {
            success = handletypeRelevanceUpdate(value);
          } else {
            success = handletypeRelevanceAdd(value);
          }
          if (success) {
            handletypeRelevanceModalVisible(false);
            setRelevanceCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          setRelevanceCurrentRow(undefined);
          handletypeRelevanceModalVisible(false);
          actionRef.current.reload();
        }}
        Support={Support}
        createModalVisible={createtypeRelevanceModalVisible}
        values={RelevanceCurrentRow || {}}
      >
      </CreatetypeRelevanceForm>
      <TabPane tab="出品类别与做法类别关联" key="1" style={{ float: 'left' }} >
        <ProTable
          actionRef={actionRef}
          rowKey="id"
          search={{
            labelWidth: 120,
          }}
          toolBarRender={() => [
            <Button
              type="primary"
              key="primary"
              onClick={() => {
                handletypeRelevanceModalVisible(true);
              }}
            >
              <PlusOutlined /> 添加
            </Button>
          ]}
          params={{
            relevanceType: 1,
          }}
          request={async (params) => {
            var datas = [];
            var total = 0;
            await getPracticeRelevance(params).then((r) => {
              datas = r.data.data;
              total = r.data.total;
            });
            return {
              data: datas,
              success: true,
              total: total,
            };
          }}
          modalVisible={createRelevanceModalVisible}
          columns={TyperelevanceColumns}
          rowSelection={{
            onChange: (_, selectedRows) => {
              setTypecurrentRow(selectedRows);
            },
          }}
        />
      </TabPane>

      <TabPane tab="出品与做法关联" key="2" style={{ float: 'left' }} >
        <ProTable
          actionRef={actionRef}
          rowKey="id"
          search={{
            labelWidth: 120,
          }}
          toolBarRender={() => [
            <Button
              type="primary"
              key="primary"
              onClick={() => {
                handleRelevanceModalVisible(true);
              }}
            >
              <PlusOutlined /> 添加
            </Button>
          ]}
          params={{
            relevanceType: 2,
          }}
          request={async (params) => {
            var datas = [];
            var total = 0;

            await getPracticeRelevance(params).then((r) => {
              datas = r.data.data;
              total = r.data.total;
            });
            return {
              data: datas,
              success: true,
              total: total,
            };
          }}
          modalVisible={createRelevanceModalVisible}
          columns={GoodsrelevanceColumns}
          rowSelection={{
            onChange: (_, selectedRows) => {
              setTypecurrentRow(selectedRows);
            },
          }}
        />
      </TabPane>
    </Tabs>
  );
};

export default PageIndex;
