import {forwardRef, memo, useCallback, useEffect, useRef, useState} from 'react'
import {
  ProCard,
  ProForm,
  ProFormDatePicker,
  ProFormSelect,
  ProFormText,
  ProFormTreeSelect
} from '@ant-design/pro-components'
import {Card, Col, Row} from 'antd'
import {styled} from 'styled-components'
import {LogicPanel} from '../../components/LogicPanel.jsx'
import {useAppDispatch, useAppSelector} from "../../../redux/configureStore";
import {selectDomains, selectModals} from "../MainPage/slice/selectors";
import {getAllModals, getModalDetail} from "../MainPage/slice/thunks";
import {CodeEditor} from "../../components/CodeEditor";
import useI18NPrefix from "../../hooks/useI18NPrefix";
const formLayoutType = "horizontal";

const component = forwardRef(({
  data,
  onSubmit
},ref) => {
  const t = useI18NPrefix('global');
  const dispatch = useAppDispatch();
  const domains = useAppSelector(selectDomains);
  const modals = useAppSelector(selectModals);
  const [tab, setTab] = useState('logic');
  const [option, setOption] = useState([]);
  const editorRef = useRef(null);

  useEffect(()=>{
    if (data){
      onDomainChange(data.domainId)
      onModalChange(data.modelId)
    }
  },[data])

  const onDomainChange = useCallback((domainId) => {
    if (domainId){
      dispatch(getAllModals({domainId}))
      ref?.current?.resetFields(['modelId'])
    }
  },[])

  const onModalChange = useCallback((id) => {
    if (id){
      dispatch(getModalDetail({
        id,
        resolve(data){
          if (data?.modelDetail){
            const {fields} = data.modelDetail
            const fieldsOptions = fields.map(({comment,fieldName})=>({
              label: comment ,
              value: fieldName,
            }))
            setOption(fieldsOptions)
          }
        }
      }))

      ref.current?.resetFields(['filters']);
    }

  },[])

  const onEditorChange=(str)=>{
    editorRef.current=str
  }

  const onFinish = (values)=>{
    onSubmit({
      id: data?.id,
      type:tab,
      ...values,
      defaultConfig:editorRef.current
    })
  }

  return (
    <>
      <ProForm
        formRef={ref}
        initialValues={data}
        layout={formLayoutType}
        onFinish={onFinish}
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 18 }}
        submitter={false}
      >
        <Card type="inner" title={t("title.baseInfo")} bordered={false}>
          <ProFormText
            name="name"
            label={t("formItem.ruleName")}
            rules={[{ required: true }]}
          />
          <ProFormText
            name="english"
            label={t("formItem.english")}
            placeholder={t("placeholder.english")}
          />
          <ProFormText
            name="description"
            label={t("formItem.description")}
            placeholder={t("placeholder.description")}
          />
          <ProFormDatePicker name="startDate" label={t("formItem.startDate")} rules={[{ required: true }]} width="100%" initialValue={new Date}/>
          <ProFormDatePicker name="stopDate" label={t("formItem.stopDate")} width="100%"/>
        </Card>

        <Card bordered={false} type="inner" title={t("title.bizRule")} style={{boxShadow:'none'}}>
          <ProFormTreeSelect
            name="domainId"
            label={t("formItem.domain")}
            rules={[{ required: true }]}
            request={async ()=>domains}
            onChange={onDomainChange}
          />
          <ProFormSelect
            name="modelId"
            label={t("formItem.model")}
            rules={[{ required: true }]}
            options={modals}
            onChange={onModalChange}
          />
          <Row>
            <Col span={4}>
              <CardLabel children={t("formItem.condition")+"："} className="required"/>
            </Col>
            <Col span={18}>
              <CustomProCard
                tabs={{
                  activeKey: tab,
                  items: [
                    {
                      key: 'logic',
                      label: t("operation.fieldsConfig"),
                      children: <LogicPanel options={option}/>,
                    },
                    {
                      key: 'custom',
                      label: t("operation.customScript"),
                      children: <CodeEditor value={data?.defaultConfig} onEditorChange={onEditorChange} width="100%" height="480"/>,
                    }
                  ],
                  onChange: (key) => {
                    setTab(key);
                  },
                }}
              />
            </Col>
          </Row>
        </Card>
      </ProForm>
    </>
  )
})
export const BizConditionForm = memo(component);

const CustomProCard=styled(ProCard)`
  .ant-pro-card-body{
    padding: 0;
  }
`

const CardLabel = styled.label`
  position: absolute;
  right: 10px;
  top: 20px;
  &.required {
    // 添加必填红色*的样式
    &::before {
      display: inline-block;
      margin-inline-end: 4px;
      color: #ff4d4f;
      font-size: 14px;
      font-family: SimSun, sans-serif;
      line-height: 1;
      content: "*";
    }
  }
`
