// 成品管理

import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { Button, Modal, Form, Input, message, Popconfirm, TreeSelect, Select, Tag, Dropdown, Space, MenuProps } from 'antd';
import { useEffect, useRef, useState } from 'react';
import finalInfoAPI from '@/api/finalService';
import { DownOutlined } from '@ant-design/icons';
import FormItem from 'antd/lib/form/FormItem';
import { ItemType } from 'rc-menu/lib/interface';
// 工艺服务
import craftsinfoAPI from '@/api/craftsinfo';
// 配方服务
import recipeAPI from '@/api/recipeService';

const final = () => {

  //定于表单
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [typeForm] = Form.useForm();

  // 定义新增弹窗
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [isModalOpen, setIsModalOpen] = useState(false);

  //  定义编辑弹窗
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const actionRef = useRef<ActionType>();

  // 定义title
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [modelTitle, setModelTitle] = useState<string>();
  // 定义列表数据
  const columns: ProColumns<FinalTypes.Info>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      tip: '规则名称是唯一的 key',
      hideInSearch: true,
      hideInTable: true,
    },

    {
      title: '成品编号',
      dataIndex: 'code',
      hideInSearch: false,
      ellipsis: true,
    },
    {
      title: '成品名称',
      dataIndex: 'name',
      hideInSearch: false,
      ellipsis: true,
    },
    {
      title: '成品配方',
      dataIndex: 'recipeName',
      ellipsis: true,
      hideInSearch: true,
    },
    {
      title: '成品工艺',
      dataIndex: 'craftName',
      ellipsis: true,
      hideInSearch: true,
    },

    {
      title: '操作',
      valueType: 'option',
   
      key: 'option',
      render: (_, record) => [
        <Button
          key="edit"
          type="primary" ghost
          
          onClick={async () => {
            setIsModalOpen(true);
            setModelTitle('成品编辑');
            const copyFormData = JSON.parse(JSON.stringify(record));
            copyFormData.state = copyFormData.state === '0';
            typeForm.setFieldsValue(copyFormData);
          }}
        >
          编辑
        </Button>,

        <Popconfirm
          key="del"
          title="确定要删除此条数据吗？"
          onConfirm={() => {

            const EnablejsonData: FinalTypes.FinalInfoDelInput = {
              id: record.id,
              // name: '',
              // code: ''
            };

            finalInfoAPI.Del(EnablejsonData).then((r:MyResponse.Content) => {
              if (r.statusCode === 200) {
                message.success(r.statusCode === 200 ? '删除成功' : r.message);
                actionRef.current?.reload();
              }
            });
          }}
          onCancel={() => {
            message.info('已取消删除');
          }}
          okText="确认"
          cancelText="关闭"
        >
          <Button type="primary" danger ghost>删除</Button>
        </Popconfirm>,
      ],
    },
  ];

  // eslint-disable-next-line react-hooks/rules-of-hooks
  useEffect(() => {
    if (isModalOpen) {
    // 下拉工艺列表信息
    const formulaList = async () => {

      const crafts = await craftsinfoAPI.selectlist();
      // console.log(crafts);

      // eslint-disable-next-line @typescript-eslint/no-use-before-define
      setformula(crafts.data);
    };
    formulaList();
     // 下拉列表信息
     const areasList = async () => {

      const recipe = await recipeAPI.selectlist();
      // console.log(recipe);

      // eslint-disable-next-line @typescript-eslint/no-use-before-define
      setareas(recipe.data);
    };
    areasList();
  }
  }, [isModalOpen]);







  const OnSubmit = async (values: FinalTypes.Info) => {

    if (values.id) {
      const response = await finalInfoAPI.Update(values);
      if (response.statusCode === 200) {
        message.success('修改成功');
        actionRef.current?.reload();
        setIsModalOpen(false);
      } else {
        message.error(JSON.stringify(response.errors) || '修改失败');
      }
    } else {
      const response = await finalInfoAPI.Add(values);
      // console.log('response', response);
      if (response.statusCode === 200) {
        message.success('添加成功');
        actionRef.current?.reload();
        setIsModalOpen(false);
      } else {
        message.error(JSON.stringify(response.errors) || '添加失败');
      }
    }
  };


  //  定义工艺列表
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [formula, setformula] = useState([])



  // 定义配方列表
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [areas, setareas] = useState([])

  return (
    <>
      <ProTable<FinalTypes.Info>
        key="myTable"
        columns={columns}
        actionRef={actionRef}
        cardBordered
        // 调用接口判断
        request={async (params = {}) => {
          const jsonData: FinalTypes.Page = {
            pageIndex: params.current || 1,
            pageSize: params.pageSize || 10,
            name: params.name || '',
            id: '',
            code: ''
          };
          const response = await finalInfoAPI.PagedList(jsonData);
          if (response.statusCode === 200) {
            return {
              data: response.data.items,
              success: true,
              total: response.data.total,
            };
          } else {
            return {
              data: [],
              success: false,
              total: 0,
            };
          }
        }}
        rowKey="id"
        pagination={{
          pageSize: 10,
        }}
        dateFormatter="string"
        headerTitle="成品列表"
        toolBarRender={() => [
          <Button
            key="button"
            type="primary"
            onClick={() => {
              typeForm.resetFields();
              setIsModalOpen(true);
              setModelTitle('新增成品');

            }}
          >
            新增成品
          </Button>,
        ]}




      />
      {/* 新增成品的model弹窗 */}
      <Modal
        key="01"
        width={800}
        title={<Tag color="#cd201f">{modelTitle}</Tag>}
        open={isModalOpen}
        onCancel={() => {
          setIsModalOpen(false);
        }}
        footer={[
          <Button
            key="back"
            onClick={() => {
              setIsModalOpen(false);
            }}
          >
            返回
          </Button>,
          <Button key="submit" form="finalForm" type="primary" htmlType="submit">
            提交
          </Button>,
        ]}
      >
        {/* 新增成品表单 */}

        <Form
          form={typeForm}
          name="basic"
          id="finalForm"

          lCol={{ span: 4 }}
          wrapperCol={{ span: 12 }}
          onFinish={OnSubmit}
          autoComplete="off"
        >
          <Form.Item label="id" name="id" hidden>
            <Input />
          </Form.Item>

          <Form.Item
            label="成品编码"
            name="code"
            rules={[{ required: true, message: '此项为必填项!' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item name="name" label="成品名称" rules={[{ required: true, message: 'Missing area' }]}>
            <Input />
          </Form.Item>

          {/* 工艺列表 */}
          <Form.Item name="craftId" label="成品工艺" rules={[{ required: true, message: 'Missing area' }]}>
            {/* <Select options={areas}  /> */}
            <Select placeholder="请选择工艺"
              // options={formula}
            >
              {
                formula.map((item:MySelectType.Select) =>{
                  return  <Select.Option value={item.key} key={item.key}>
                     <span>{item.value}</span>
                  </Select.Option>
                })
              }
             </Select>


          </Form.Item>
          {/* 配方列表 */}
          <Form.Item name="recipeId" label="成品配方" rules={[{ required: true, message: 'Missing area' }]}>
            {/* <Select options={formula}  /> */}
            <Select placeholder="请选择成品配方"
              // options={areas}
              >
              {
                areas.map((item:MySelectType.Select) =>{
                  return  <Select.Option value={item.key} key={item.key}>
                     <span>{item.value}</span>
                  </Select.Option>
                })
              }
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </>


  );
};

export default final;
