/**
 * 工单基础信息管理
 * @param Page
 * @returns
 */
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { Button, Modal, Form, Input, message, Popconfirm, Tag, DatePicker as TDatePicker, Select, Steps, StepsProps, Popover, ConfigProvider, List } from 'antd';
import { useEffect, useRef, useState } from 'react';
import WorkInfoAPI from '@/api/workService';
import FinalAPI from '@/api/finalService';
import ProductLineAPI from '@/api/productlineService';
import styles from "./index.less";
import dayjs from 'dayjs'



const DatePicker: any = TDatePicker;
const Stepitems = [
  {
    title: '草稿',
    description: '',
  },
  {
    title: '已下发',
    description: '',
  },
  {
    title: '已接受',
    description: '',
  },
  {
    title: '已启动',
    description: '',
  },
  {
    title: '已完成',
    description: '',
  }
];


export default () => {


  //表单
  const [typeForm] = Form.useForm();
  const [modelTitle, setModelTitle] = useState<string>();
  const [finalData, setFinalData] = useState<MySelectType.Select[]>([])
  const [lineData, setLineData] = useState<MySelectType.Select[]>([])
  const [workStatusList,setWorkStatusList] = useState([])
  //编辑/新增弹窗
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isModalStatusOpen, setIsModalStatusOpen] = useState(false);
  const actionRef = useRef<ActionType>();
  const columns: ProColumns<WorkInfoTypes.WorkInfoOutput>[] = [
    {
      title: '工单编码',
      dataIndex: 'id',
      hideInSearch: true,
      width: 140,
      align: 'center',
    },
    {
      title: '线路名称',
      dataIndex: 'lineName',
      ellipsis: true,
      align: 'center',
      width: 100
    },
    {
      title: '成品名称',
      dataIndex: 'finalName',
      align: 'center',
      ellipsis: true,
    },
    {
      title: '产量',
      dataIndex: 'number',
      ellipsis: true,
      hideInSearch: true,
      align: 'center',
      width: 100
    },
    {
      title: '进度',
      dataIndex: 'status',
      ellipsis: true,
      align: 'center',
      hideInSearch: true,
      render(_, record) {
        return <ConfigProvider
          theme={{
            components: {
              Steps: {
                navArrowColor: 'red',
                descriptionMaxWidth: 50
              },
            },
          }}
        >
          <Steps
            progressDot
            direction='horizontal'

            type='default'
            current={record.status}
            size='small'
            items={Stepitems}
          />
        </ConfigProvider>
      },
    },
    {
      title: '创建日期',
      dataIndex: 'createTime',
      ellipsis: true,
      hideInSearch: true,
      width: 140
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      render: (_, record) => {
        switch (record.status) {
          case 0:
          
            return [
            <Button
              key="edit"
              type="primary" ghost
              onClick={async () => {
                setIsModalOpen(true);
                setModelTitle('编辑信息');
                const copyFormData = JSON.parse(JSON.stringify(record));
                //  copyFormData.repairDate =dayjs(record.repairDate)
                console.log('record', record);
  
                typeForm.setFieldsValue(copyFormData);
              }}
            >
              编辑
            </Button>,
            <Popconfirm
            key="workdel"
            title="确定要删除此工单吗？"
            onConfirm={() => {
              const EnablejsonData: WorkInfoTypes.WorkInfoDelInput = {
                id: record.id,
              };
              WorkInfoAPI.Del(EnablejsonData).then((r) => {
                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>
            ,
            <Popconfirm
              key="workedit"
              title="确定要下发此工单吗？"
              onConfirm={() => {
                WorkInfoAPI.Publish(record.id).then((r) => {
                  if (r.statusCode === 200) {
                    message.success(r.statusCode === 200 ? '下发成功' : r.message);
                    actionRef.current?.reload();
                  }
                });
              }}
              onCancel={() => {
                message.info('已取消操作');
              }}
              okText="确认"
              cancelText="关闭"
            >
              <Button type="primary" ghost>下发</Button>
            </Popconfirm>  ]
          case 1:
            return [ <Popconfirm
              key="forcedend"
              title="确定要强制结束此工单吗？"
              onConfirm={() => {
                WorkInfoAPI.ForcedEnd(record.id).then((r) => {
                  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>]
          case 2:
            return [<Popconfirm
              key="forcedend"
              title="确定要强制结束此工单吗？"
              onConfirm={() => {
                WorkInfoAPI.ForcedEnd(record.id).then((r) => {
                  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>]
          case 3:
            return [<Popconfirm
              key="forcedend"
              title="确定要强制结束此工单吗？"
              onConfirm={() => {
                WorkInfoAPI.ForcedEnd(record.id).then((r) => {
                  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>]
          case 4:
            return [<Button key="workStatusUpdate" type="primary"  ghost onClick={()=>{
              setIsModalStatusOpen(true)
              WorkInfoAPI.UpdateStatusList(record.id).then((res: MyResponse.Content)=>{
                if (res.statusCode===200) {
                  setWorkStatusList(res.data)
                }
              })
            }}>状态变更记录</Button>]
          default:
            return []
        }
}
     },
   ];




//初始化
useEffect(() => {
  FinalAPI.SelectList().then((res: MyResponse.Content) => {
    if (res.statusCode === 200) {
      setFinalData(res.data)
    }
  })
  ProductLineAPI.selectlist().then((res: MyResponse.Content) => {
    if (res.statusCode === 200) {
      setLineData(res.data)
    }
  })
}, [])
/*
 *表单提交
 */
const OnSubmit = async (values: WorkInfoTypes.WorkInfoOutput) => {

  if (values.id) {
    const response = await WorkInfoAPI.Update(values);
    if (response.statusCode === 200) {
      message.success('修改成功');
      actionRef.current?.reload();
      setIsModalOpen(false);
    } else {
      message.error(JSON.stringify(response.errors) || '修改失败');
    }
  } else {
    const response = await WorkInfoAPI.Add(values);
    console.log('response', response);
    if (response.statusCode === 200) {
      message.success('添加成功');
      actionRef.current?.reload();
      setIsModalOpen(false);
    } else {
      message.error(JSON.stringify(response.errors) || '添加失败');
    }
  }
};
return (
  <>
    <ProTable<WorkInfoTypes.WorkInfoOutput>
      key="myTable"

      columns={columns}
      actionRef={actionRef}
      cardBordered
      request={async (params = {}) => {
        const jsonData: WorkInfoTypes.Page = {
          pageIndex: params.current || 1,
          pageSize: params.pageSize || 10,
          name: params.name || '',
          code: params.code
        };
        const response = await WorkInfoAPI.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>,
      ]}
    />
    <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="deviceInfoForm" type="primary" htmlType="submit">
          提交
        </Button>,
      ]}
    >
      <Form
        form={typeForm}
        name="basic"
        id="deviceInfoForm"

        onFinish={OnSubmit}
        autoComplete="off"
      >
        <Form.Item label="id" name="id" hidden>
          <Input />
        </Form.Item>

        {/* <Form.Item
             label="工单名称"
             name="name"
             rules={[{ required: true, message: '此项为必填项!' }]}
           >
             <Input />
           </Form.Item> */}
        <Form.Item label="成品" name="finalId" rules={[{ required: true, message: '此项为必填项!' }]} >
          <Select>

            {finalData.map((item, index) => {
              return <Select.Option value={item.key} key={item.key}>
                <span>{item.value}</span>
              </Select.Option>
            })}
          </Select>
        </Form.Item>
        <Form.Item label="产线" name="lineId" rules={[{ required: true, message: '此项为必填项!' }]}>
          <Select>
            {lineData.map((item, index) => {
              return <Select.Option value={item.key} key={item.key}>
                <span>{item.value}</span>
              </Select.Option>
            })}
          </Select>
        </Form.Item>
        <Form.Item label="产量" name="number" rules={[{ required: true, message: '此项为必填项!' }]} >
          <Input />
        </Form.Item>
      </Form>
    </Modal>
    <Modal
      key="workStatusList"
      width={800}
      title={<Tag color="#cd201f">状态变更记录</Tag>}
      open={isModalStatusOpen}
      footer={false}
      onCancel={() => {
        setIsModalStatusOpen(false);
      }}
>

<List 
dataSource ={workStatusList}
renderItem={(item, index) => (
  <List.Item>
   {item.status }
   {item.createTime }
  </List.Item>
   )}
>

</List>

</Modal>
  </>
);
 };
