"use client";

import React, { useEffect, useState } from 'react';
import { Button, Form, Input, InputNumber, Modal, Select, message } from 'antd';
import { Loading } from "@/components/dashboard/loading";
import service from '@/lib/http/service';
import toast from 'react-hot-toast';
import { StaffsInfo, addStaff } from '@/lib/http/staff';
import { useRouter } from 'next/navigation';






export interface CreateFormProps {
  onCancel?: () => void;
  onSubmit?: (values: StaffsInfo) => void;
  createModalVisible?: boolean;
}

const FormItem = Form.Item;

const formLayout = {
  labelCol: { span: 7 },
  wrapperCol: { span: 13 },
};


/**
 * 添加节点
 * @param fields
 */
const handleAdd = async (fields: StaffsInfo) => {
  const hide = message.loading('正在添加');
  try {
    // fields.password = md5(fields.password)
    // fields.user_alias = fields.user_name
    console.log("----------:", fields)

    await addStaff({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

const CreateForm: React.FC<CreateFormProps> = (props) => {
  const [form] = Form.useForm();

  const [initLoading, setInitLoading] = useState(false);

  const {
    onSubmit,
    onCancel,
    createModalVisible,
  } = props;

  useEffect(() => {
    if (form && !createModalVisible) {
      form.resetFields();
    }
  }, [props.createModalVisible]);


  const handleSubmit = () => {
    if (!form) return;
    form.submit();
  };

  // const handleFinish = (values: JobListItem) => {
  //   if (onSubmit) {
  //     onSubmit(values);
  //   }
  // };



  const handleFinish = async (value: StaffsInfo) => {
    console.log("onFinish ---", value);

    await service.post('/api/v1/customer/create/staff', {

      //     "name":"我的AI员工1号",     //员工名称(必填)
      //     "org_name":"主板销售部",    //组织名称(必填)
      //     "tone":"亲切且专业",        //语气
      //     "output_length":"简短",    //回复长度
      //     "description":"销冠的潜质", //员工描述
      //     "avatar_url":"https://www.pic.com/avatar001.jpg" //头像URL

      name: value.name,
      org_name: value.org_name,
      tone: value.tone,
      output_length: value.output_length,
      description: value.description,
      avatar_url: value.avatar_url,
    }, {
      headers: {
        // 'Authorization': token
      }
    }).then(function (result: any) {


      console.log("result:", result)

      if (result && result.header.code != 0) {

        toast.error(result.header.message)
        return
      }

      // setInitLoading(false);

      // categoriesRef.current.values


      const tags = result.data.list

      // getNewListFunc(1)


    }).catch((err) => {
      // setInitLoading(false);

    });
  };

  const renderContent = () => {
    return (
      <>
        <Form.Item label="版本">
          <Select defaultValue="demo" disabled>
            <Select.Option value="demo">通用版本</Select.Option>
            <Select.Option value="demo2">高级版本</Select.Option>
          </Select>
        </Form.Item>

        <Form.Item
          label="设置组织名称"
          name="org_name"
          rules={[{ required: true }]}
        >
          <Input
            // variant="borderless"
            // className="placeholder:text-[#808080] "
            // style={{
            //   background: "#F5F5F5",
            //   borderRadius: "0",
            //   // width: 360

            // }}
            placeholder="设置名称"
          />
        </Form.Item>

        <Form.Item
          label="员工名称(必填)"
          name="name"
          rules={[{ required: true }]}
        >
          <Input
            // variant="borderless"
            // className="placeholder:text-[#808080] "
            // style={{
            //   background: "#F5F5F5",
            //   borderRadius: "0",
            //   // width: 360

            // }}
            placeholder="设置名称"
          />
        </Form.Item>


        <Form.Item
          label="客服语气"
          name="tone"
        // rules={[{ required: true }]}
        >

          {/* communication tones（交流语气）：友好且真诚friendly and sincere, 专业且稳重professional and cautious, 清晰且直接clear and direct */}
          {/* defaultValue="friendly and sincere" */}
          <Select id="tone" placeholder={'请选择语气'}>
            <Select.Option value="friendly and sincere">友好且真诚</Select.Option>
            <Select.Option value="professional and cautious">专业且稳重</Select.Option>
            <Select.Option value="clear and direct">清晰且直接</Select.Option>
          </Select>
        </Form.Item>

        <Form.Item
          label="回答长度"
          name="output_length"
        // rules={[{ required: true }]}
        >
          <Select id="output_length" placeholder={'请选择回答长度'}>
            <Select.Option value="short">默认(简短)</Select.Option>
            <Select.Option value="medium">中等</Select.Option>
            <Select.Option value="longer">较长</Select.Option>
          </Select>
        </Form.Item>

        <Form.Item
          label="上传LOGO"
          name="avatar_url"
        // rules={[{ required: true }]}
        >
          {/* <Select defaultValue="one" >
                  <Select.Option value="one">默认</Select.Option>
                </Select> */}
          <Input
            // variant="borderless"
            // className="placeholder:text-[#808080] "
            // style={{
            //   background: "#F5F5F5",
            //   borderRadius: "0",
            //   // width: 360

            // }}
            placeholder="设置Logo"
          />

        </Form.Item>

        <Form.Item label="员工描述"
          name="description"
        // wrapperCol={{
        //   offset: 2,
        //   span: 16
        // }}
        // validateStatus="error"
        // hasFeedback
        // help="Should have something"
        >
          <Input.TextArea
            // allowClear
            // showCount 
            // style={{
            //   background: "#fff",
            //   borderRadius: "0",
            //   border: "none",
            //   height: "100px",
            // }}
            className=""
          />
        </Form.Item>



        {/* <Button type="primary" htmlType="submit" className="bg-[#000] w-full rounded">
                创建AI客服


              </Button> */}

        <Form.Item wrapperCol={{ span: 12, offset: 12 }}>
          <Button
            // disabled={initLoading || !form.formState.isValid}

            disabled={
              initLoading
              // ||
              // !form.isFieldsTouched(true) ||
              // !!form.getFieldsError().filter(({ errors }) => errors.length).length
            }
            className="mt-4 bg-[#000] text-[#fff]"
            htmlType="submit"
          >
            {initLoading ? <Loading /> : "创建AI客服"}
          </Button>
        </Form.Item>




      </>
    );
  };

  const modalFooter = { okText: '保存', onOk: handleSubmit, onCancel };

  const router = useRouter();

  return (
    // <Modal
    //   forceRender
    //   destroyOnClose
    //   title="新建职位信息"
    //   open={createModalVisible}
    //   {...modalFooter}
    // >
    //   <Form
    //     {...formLayout}
    //     form={form}
    //     onFinish={handleFinish}
    //   >
    //     {renderContent()}
    //   </Form>
    // </Modal>

    <div>

      <Form
        {...formLayout}
        form={form}
        onFinish={async (e) => {

          if (await handleAdd(e)) {
            router.push("/manage/staffs")
          }

        }}
      >
        {renderContent()}
      </Form>
    </div>
  );
};

export default CreateForm;


