/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2022-07-13 15:27:51
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2025-02-28 18:15:16
 * @FilePath: /KC-MiddlePlatform/src/pages/platform/setting/indicatorMana/drawer.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import React, { useEffect, useRef, useState } from 'react';
import { Drawer, Cascader, Button, Form } from 'antd';
import ProForm, { ProFormCascader, ProFormDependency, ProFormDigit, ProFormInstance, ProFormRadio, ProFormSelect, ProFormText, ProFormTextArea } from '@ant-design/pro-form';

import './style.less';
import { getIndicatorDictionary, IndicatorDictionaryDataType } from '@/service/dictionary';
import { DefaultOptionType } from 'antd/lib/select';
import { getHospDepartment } from '@/service/department';
import { getUsers } from '@/service/user';
import { addIndicatorManaList } from '@/service/indicator';
import { createFromIconfontCN } from '@ant-design/icons';

export interface IndicatorDrawerForm {
  visible: boolean;
  record?: any;
  onVisibleChange?: (bool: boolean) => void;
  onFinish?: (formData: any) => void;
  onChange?: (data: any) => void;
  actType: 'EDIT' | 'ADD';
}

const IconFont = createFromIconfontCN({
  scriptUrl: '',
});

const DrawerForm = (props: IndicatorDrawerForm) => {
  const { visible = false, onChange, onFinish, record, onVisibleChange, actType } = props;

  const [_visible, _setVisible] = useState(false);

  const [renderType, set_renderType] = useState<'ADD' | 'EDIT'>('ADD');

  const [dirData, set_dirData] = useState<IndicatorDictionaryDataType[]>([]);

  const baseInfoformRef = useRef<ProFormInstance>();
  const manaInfoformRef = useRef<ProFormInstance>();
  const showSetInfoformRef = useRef<ProFormInstance>();
  const adminInfoformRef = useRef<ProFormInstance>();

  const showDrawer = () => {
    _setVisible(true);
    onVisibleChange && onVisibleChange(true);
  };

  const onClose = () => {
    _setVisible(false);
    onVisibleChange && onVisibleChange(false);
  };

  const commitHandle = () => {
    let commitData: any[] = [];
    if (baseInfoformRef.current && baseInfoformRef.current.validateFieldsReturnFormatValue) {
      baseInfoformRef.current?.validateFieldsReturnFormatValue().then((val) => {
        commitData.push({
          baseInfoformRef: val,
        });
      });
    }

    if (manaInfoformRef.current && manaInfoformRef.current.validateFieldsReturnFormatValue) {
      manaInfoformRef.current?.validateFieldsReturnFormatValue().then((val) => {
        console.log('manaInfoformRef', val);
        //_indicatorTypeList
        // manaInfoformRef.current?.getFieldsValue();
        // console.log('w',manaInfoformRef.current?.getFieldValue('_indicatorTypeList'))
        const _indicatorTypeLists = manaInfoformRef.current?.getFieldValue('_indicatorTypeList');
        const _indicatorExternalList = manaInfoformRef.current?.getFieldValue('_indicatorExternalList');

        // console.log({_indicatorTypeLists,_indicatorExternalList});

        commitData.push({
          manaInfoformRef: {
            ...val,
            indicatorTypeList: _indicatorTypeLists ? _indicatorTypeLists : val.indicatorTypeList ? val.indicatorTypeList.map((t: any) => t[t.length - 1]) : [],
            indicatorExternalList: _indicatorExternalList ? _indicatorExternalList : val.indicatorExternalList ? val.indicatorExternalList.map((t: any) => t[t.length - 1]) : [],
          },
        });
      });
    }
    if (showSetInfoformRef.current && showSetInfoformRef.current.validateFieldsReturnFormatValue) {
      showSetInfoformRef.current?.validateFieldsReturnFormatValue().then((val) => {
        // console.log('showSetInfoformRef',val);
        commitData.push({
          showSetInfoformRef: val,
        });
      });
    }
    if (adminInfoformRef.current && adminInfoformRef.current.validateFieldsReturnFormatValue) {
      adminInfoformRef.current?.validateFieldsReturnFormatValue().then((val) => {
        const _indicatorMenuList = adminInfoformRef.current?.getFieldValue('_indicatorMenuList');
        if (val.indicatorMenuList) {
          commitData.push({
            adminInfoformRef: {
              ...val,
              indicatorMenuList: _indicatorMenuList ? _indicatorMenuList : val.indicatorMenuList ? val.indicatorMenuList.map((t: any) => t[t.length - 1]) : [],
            },
          });
        }
      });
    }

    setTimeout(() => {
      const hasBaseInfoformRef = commitData.some((item) => item.hasOwnProperty('baseInfoformRef'));
      const hasAdminInfoformRef = commitData.some((item) => item.hasOwnProperty('adminInfoformRef'));
      if (hasBaseInfoformRef && hasAdminInfoformRef) {
        onFinish && onFinish(commitData);
      }
    }, 1000);
  };

  const getDataFromDir = async () => {
    const dirData = await getIndicatorDictionary();
    set_dirData(dirData);
  };

  const getSelectorData = (code: string, type?: 'Cascader') => {
    const result = dirData.filter((t) => t.code == code);

    if (type == 'Cascader' && result.length > 0) {
      return result[0].children;
    }

    if (result.length > 0) {
      return result[0].children.map((t) => ({ label: t.name, value: t.code }));
    }
    return [];
  };

  const setFormInit = (key: string) => {
    if (key == 'indicatorTypeList') {
      if (record && record.indicatorTypeList) {
        const indicatorTypeListVal = record.indicatorTypeList ? record.indicatorTypeList.map((t: string) => t.split('/')) : [];
        const _indicatorTypeList = indicatorTypeListVal.map((t: any) => t.slice(1, t.length));
        // console.log({indicatorTypeListVal,_indicatorTypeList})
        return _indicatorTypeList;
      }
    }
    if (key == 'indicatorMenuList') {
      if (record && record.indicatorMenuList) {
        const a = record.indicatorMenuList ? record.indicatorMenuList.map((t: string) => t.split('/')) : [];
        const b = a.map((t: any) => t.slice(1, t.length));
        // console.log({a,b})
        return b;
      }
    }

    if (key == 'indicatorExternalList') {
      if (record && record.indicatorExternalList) {
        const a = record.indicatorExternalList ? record.indicatorExternalList.map((t: string) => t.split('/')) : [];
        const b = a.map((t: any) => t.slice(1, t.length));
        // console.log({a,b})
        return b;
      }
    }
  };

  useEffect(() => {
    if (visible) {
      getDataFromDir();
    }
    _setVisible(visible);
  }, [visible]);

  useEffect(() => {
    set_renderType(actType);
  }, [actType]);

  return (
    <div>
      <Drawer
        className="DrawerForm"
        width={1000}
        title={renderType == 'ADD' ? '新增指标' : '管理信息'}
        placement="right"
        onClose={onClose}
        open={_visible}
        destroyOnClose
        footer={false}
        headerStyle={{ display: 'none' }}
        // footer={
        //     <div>
        //         <Button style={{ marginRight: 20 }} onClick={() => onClose()}>取消</Button>
        //         <Button type="primary" onClick={() => commitHandle()}>确定</Button>
        //     </div>
        // }
        bodyStyle={{ background: 'rgba(153, 166, 191, 0.1)', padding: 0, scrollbarWidth: 'thin' }}
      >
        <div className="drawerHeader">
          <div className="drawerTitle">
            <svg
              style={{ marginRight: 14, position: 'relative', top: 4, cursor: 'pointer' }}
              onClick={() => _setVisible(false)}
              viewBox="0 0 1024 1024"
              version="1.1"
              xmlns="http://www.w3.org/2000/svg"
              p-id="41844"
              width="18"
              height="18"
            >
              <path
                d="M793.024 200.96l27.392 27.392a12.8 12.8 0 0 1 0 18.112L555.52 510.784l267.392 266.752a12.8 12.8 0 0 1 0 18.112l-27.392 27.328a12.8 12.8 0 0 1-18.112 0L510.08 556.224l-263.424 262.784a12.8 12.8 0 0 1-18.112 0l-27.392-27.392a12.8 12.8 0 0 1 0-18.112l263.36-262.72-260.864-260.288a12.8 12.8 0 0 1 0-18.112l27.392-27.392a12.8 12.8 0 0 1 18.048 0L510.08 465.344l264.96-264.32a12.8 12.8 0 0 1 18.048 0z"
                p-id="41845"
                fill="#17181A"
              ></path>
            </svg>
            {/* <IconFont style={{cursor:'pointer',marginRight:14,fontSize:16,color:'red'}} type='iconquxiao'  /> */}
            {record && record.name}
          </div>
          <div className="btnGroup">
            <span onClick={() => onClose()}>取消</span>
            <span className="primary" onClick={() => commitHandle()}>
              确定
            </span>
          </div>
        </div>
        <div className="drawerContent">
          <div className="card">
            <div className="cardTitle">指标基本信息</div>
            <div className="formContent">
              <ProForm
                layout={'vertical'}
                formRef={baseInfoformRef}
                grid={true}
                initialValues={renderType == 'ADD' ? { attributeType: 1 } : { ...record }}
                rowProps={{
                  gutter: [16, 0],
                }}
                submitter={{
                  render: () => null,
                }}
              >
                <ProFormText colProps={{ md: 12, xl: 8 }} name="name" label="指标名称" placeholder="请输入" fieldProps={{}} rules={[{ required: true, message: '这是必填项' }]} />
                <ProFormText colProps={{ md: 12, xl: 8 }} name="code" label="指标编码" placeholder="请输入" rules={[{ required: true, message: '这是必填项' }]} />
                <ProFormText colProps={{ md: 12, xl: 8 }} name="nationalCode" label="国家编码" placeholder="请输入" />
                <ProFormTextArea
                  colProps={{ md: 12, xl: 16 }}
                  name="targetDefinition"
                  label="指标定义"
                  placeholder="请输入"
                  rules={[{ required: true, message: '这是必填项' }]}
                  fieldProps={{
                    allowClear: true,
                    autoSize: true,
                  }}
                />
                <ProFormSelect
                  colProps={{ md: 12, xl: 8 }}
                  name="dimension"
                  label="指标维度"
                  fieldProps={{ size: 'small' }}
                  options={[
                    {
                      label: '结构面',
                      value: 1,
                    },
                    {
                      label: '过程面',
                      value: 2,
                    },
                    {
                      label: '结果面',
                      value: 3,
                    },
                  ]}
                  placeholder="请选择"
                />
                <ProFormRadio.Group
                  name="attributeType"
                  label="指标属性"
                  colProps={{ md: 12, xl: 24 }}
                  options={[
                    {
                      label: '定性',
                      value: 1,
                    },
                    {
                      label: '定量',
                      value: 2,
                    },
                  ]}
                />
                <ProFormDependency name={['attributeType']}>
                  {({ attributeType }) => {
                    if (attributeType == 2) {
                      return (
                        <>
                          <ProFormSelect
                            colProps={{ md: 12, xl: 8 }}
                            name="directionType"
                            label="管理指向"
                            fieldProps={{ size: 'small' }}
                            options={[
                              {
                                label: '正向',
                                value: 1,
                              },
                              {
                                label: '负向',
                                value: 2,
                              },
                              {
                                label: '区间',
                                value: 3,
                              },
                              {
                                label: '监测达标',
                                value: 4,
                              },
                              {
                                label: '监测比较',
                                value: 5,
                              },
                            ]}
                            placeholder="请选择"
                          />
                          <ProForm.Group colProps={{ md: 12, xl: 8 }}>
                            <div style={{ display: 'flex', flexDirection: 'row', justifyContent: 'center', alignItems: 'center' }}>
                              <div>
                                <ProFormDigit label="指标区间" name="lowerLimit" min={0} max={10000} placeholder="最小值" fieldProps={{ precision: 3 }} />
                              </div>
                              -
                              <div style={{ position: 'relative', top: 10 }}>
                                <ProFormDigit name="upperLimit" min={0} max={10000} placeholder="最大值" fieldProps={{ precision: 3 }} />
                              </div>
                            </div>
                          </ProForm.Group>

                          <ProFormSelect
                            colProps={{ md: 12, xl: 8 }}
                            name="unit"
                            label="单位"
                            fieldProps={{ size: 'small' }}
                            request={async () => {
                              const dirData = await getIndicatorDictionary();
                              const result = dirData.filter((t) => t.code == 'Department');

                              if (result.length > 0) {
                                return result[0].children.map((t) => ({ label: t.name, value: t.code }));
                              }
                              return [];
                            }}
                            placeholder="请选择"
                          />

                          <ProFormDependency name={['unit']}>
                            {({ unit }) => {
                              return unit == '173' || unit == '326' ? (
                                <ProForm.Group colProps={{ md: 12, xl: 24 }}>
                                  <div style={{ display: 'flex', flexDirection: 'row', justifyContent: 'center', alignItems: 'center' }}>
                                    <div>
                                      <ProFormText name="molecule" label="公式" width={437} placeholder="请输入分子" />
                                    </div>
                                    /
                                    <div style={{ position: 'relative', top: 10 }}>
                                      <ProFormText width={437} name="denominator" placeholder="请输入分母" />
                                    </div>
                                    {unit == '173' ? `*100%` : `‰`}
                                  </div>
                                </ProForm.Group>
                              ) : (
                                <ProForm.Group colProps={{ md: 12, xl: 24 }}>
                                  <ProFormText name="molecule" label="公式" placeholder="请输入公式" />
                                </ProForm.Group>
                              );
                            }}
                          </ProFormDependency>

                          <ProFormSelect
                            colProps={{ md: 12, xl: 8 }}
                            name="moleculeSourcType"
                            label="分子数据来源"
                            fieldProps={{ size: 'small' }}
                            options={[
                              {
                                label: '定期填报',
                                value: 1,
                              },
                              {
                                label: '表单导入',
                                value: 2,
                              },
                              {
                                label: '系统导入',
                                value: 3,
                              },
                              {
                                label: '异动时填报',
                                value: 4,
                              },
                            ]}
                            placeholder="请选择"
                          />
                          {/* <ProFormText colProps={{ md: 12, xl: 8 }} name="moleculeSourcDesc" label='分子来源说明' placeholder="请输入" /> */}
                          <ProFormTextArea
                            colProps={{ md: 12, xl: 16 }}
                            name="moleculeSourcDesc"
                            label="分子来源说明"
                            placeholder="请输入"
                            fieldProps={{
                              allowClear: true,
                              autoSize: true,
                              size: 'small',
                            }}
                          />
                          <ProFormSelect
                            colProps={{ md: 12, xl: 8 }}
                            name="denominatorSourceType"
                            label="分母数据来源"
                            fieldProps={{ size: 'small' }}
                            options={[
                              {
                                label: '定期填报',
                                value: 1,
                              },
                              {
                                label: '表单导入',
                                value: 2,
                              },
                              {
                                label: '系统导入',
                                value: 3,
                              },
                              {
                                label: '异动时填报',
                                value: 4,
                              },
                            ]}
                            placeholder="请选择"
                          />

                          {/* <ProFormText colProps={{ md: 12, xl: 8 }} name="denominatorSourceDesc" label='分母来源说明' placeholder="请输入" /> */}
                          <ProFormTextArea
                            colProps={{ md: 12, xl: 16 }}
                            name="denominatorSourceDesc"
                            label="分母来源说明"
                            placeholder="请输入"
                            fieldProps={{
                              allowClear: true,
                              autoSize: true,
                            }}
                          />
                        </>
                      );
                    }
                  }}
                </ProFormDependency>
              </ProForm>
            </div>
          </div>

          <div className="card">
            <div className="cardTitle">指标管理信息</div>
            <div className="formContent">
              <ProForm
                formRef={manaInfoformRef}
                layout={'vertical'}
                autoFocusFirstInput={false}
                grid={true}
                initialValues={
                  renderType == 'ADD'
                    ? { indicatorTypeList: [], indicatorExternalList: [] }
                    : {
                        ...record,
                        indicatorMenuList: setFormInit('indicatorMenuList'),
                        // indicatorTypeList:record.indicatorTypeList?record.indicatorTypeList.map((t:string)=>t.split('/')).slice(1,record.indicatorTypeList.map((t:string)=>t.split('/')).length - 1):[],
                        indicatorTypeList: setFormInit('indicatorTypeList'),
                        indicatorExternalList: setFormInit('indicatorExternalList'),
                        // indicatorCommitteeList:record.indicatorCommitteeList[0]?record.indicatorCommitteeList[0].split('/'):[]
                      }
                }
                rowProps={{
                  gutter: [16, 0],
                }}
                submitter={{
                  render: () => null,
                }}
              >
                <ProFormSelect
                  colProps={{ md: 12, xl: 8 }}
                  name="divisionId"
                  label="负责科室"
                  fieldProps={{ size: 'small' }}
                  request={async () => {
                    const data = await getHospDepartment();
                    return data.map((t) => ({ label: t.name, value: t.code }));
                  }}
                  placeholder="请选择"
                />
                <ProFormSelect
                  colProps={{ md: 12, xl: 8 }}
                  name="principalId"
                  label="负责人"
                  fieldProps={{ size: 'small' }}
                  request={async () => {
                    const data = await getUsers({ pageSize: 1000, current: 1 });
                    return data.list.map((t) => ({ label: t.name, value: t.code }));
                  }}
                  placeholder="请选择"
                />
                {/* <ProFormSelect
                                colProps={{ md: 12, xl: 8 }}
                                name="principalId"
                                label="负责人"
                                request={async ()=>{
                                    const data = await getUsers({pageSize:1000,current:1});
                                       return data.list.map(t=>({label:t.name,value:t.code}))
                                }}
                                placeholder="请选择"
                            /> */}

                <ProFormSelect
                  colProps={{ md: 12, xl: 8 }}
                  name="manageLevel"
                  label="指标管理级别"
                  fieldProps={{
                    // mode: 'multiple',
                    size: 'small',
                    maxTagCount: 'responsive',
                  }}
                  options={[
                    {
                      label: '院级指标/日常',
                      value: 0,
                    },
                    {
                      label: '院级指标/重点监测',
                      value: 1,
                    },
                    {
                      label: '科级指标/日常',
                      value: 2,
                    },
                    {
                      label: '科级指标/重点监测',
                      value: 3,
                    },
                  ]}
                  placeholder="请选择"
                />
                <ProFormSelect
                  colProps={{ md: 12, xl: 8 }}
                  name="analysisType"
                  label="分析方式"
                  fieldProps={{ size: 'small' }}
                  options={[
                    {
                      label: '数值',
                      value: 1,
                    },
                    {
                      label: '监测比较',
                      value: 2,
                    },
                    {
                      label: '目标值达标分析',
                      value: 3,
                    },
                    {
                      label: '数值趋势分析',
                      value: 4,
                    },
                    {
                      label: '标准差异常分析',
                      value: 5,
                    },
                    {
                      label: '四分位数值分析',
                      value: 6,
                    },
                  ]}
                  placeholder="请选择"
                />
                {/* <Form.Item  >
                                    <DiyFormCascader data={getSelectorData('IndicatorType', 'Cascader')} />
                            </Form.Item> */}

                <ProFormCascader
                  colProps={{ md: 12, xl: 8 }}
                  name="indicatorTypeList"
                  label="指标类别"
                  fieldProps={{
                    size: 'small',
                    maxTagCount: 'responsive',
                    multiple: true,
                    showCheckedStrategy: 'SHOW_CHILD',
                    fieldNames: { label: 'name', value: 'code', children: 'children' },
                    options: getSelectorData('IndicatorType', 'Cascader'),
                    onChange(value, selectOptions) {
                      console.log({ value, selectOptions });

                      var nodes: any[] = [];

                      function parseTreeJson(array: any[]) {
                        if (!array) return [];
                        for (let index = 0; index < array.length; index++) {
                          const element = array[index];
                          // 判断element.children是对象
                          if (element.children && typeof element.children == 'object') {
                            parseTreeJson(element.children);
                          } else {
                            // 判断是否为子节点
                            if (!(element.children || typeof element.children == 'object')) {
                              // 获得符合的 node
                              nodes.push(element);
                            }
                          }
                        }
                      }

                      if (value.length > 0) {
                        for (let index = 0; index < value.length; index++) {
                          let current = value[index];
                          let key = current[current.length - 1];
                          const result = selectOptions[index].filter((t: any) => t.code == key);

                          if (result[0].children) {
                            //非直接叶子节点
                            parseTreeJson(result[0].children);
                          }
                          if (!result[0].children) {
                            //直接叶子节点
                            nodes.push({ code: result[0].code });
                          }
                        }
                      }

                      const codes = nodes.map((t) => t.code);
                      manaInfoformRef.current?.setFieldsValue({ _indicatorTypeList: codes });
                    },
                  }}
                />
                <ProFormText label="管理目标值" colProps={{ md: 12, xl: 8 }} name="targetValue" />

                <ProFormSelect
                  colProps={{ md: 12, xl: 8 }}
                  name="indicatorDepartmentList"
                  label="职能科室归属"
                  fieldProps={{
                    mode: 'multiple',
                    size: 'small',
                    maxTagCount: 'responsive',
                  }}
                  options={getSelectorData('IndicatorDepartment') as DefaultOptionType[]}
                  placeholder="请选择"
                />

                <ProFormDigit colProps={{ md: 12, xl: 8 }} name="reference" label="同级参考值" placeholder="请输入" />
                {/* <ProFormText colProps={{ md: 12, xl: 8 }} name="referenceDesc" label="参考值来源说明" placeholder="请输入" /> */}
                <ProFormTextArea
                  colProps={{ md: 12, xl: 8 }}
                  name="referenceDesc"
                  label="参考值来源说明"
                  placeholder="请输入"
                  fieldProps={{
                    allowClear: true,
                    autoSize: true,
                    size: 'small',
                  }}
                />

                <ProFormSelect
                  colProps={{ md: 12, xl: 8 }}
                  name="indicatorCommitteeList"
                  label="委员会归属"
                  fieldProps={{
                    size: 'small',
                    mode: 'multiple',
                    maxTagCount: 'responsive',
                  }}
                  options={getSelectorData('IndicatorCommittee') as DefaultOptionType[]}
                  placeholder="请选择"
                />

                <ProFormCascader
                  colProps={{ md: 12, xl: 8 }}
                  name="indicatorExternalList"
                  label="外部指标"
                  fieldProps={{
                    size: 'small',
                    multiple: true,
                    maxTagCount: 'responsive',
                    fieldNames: { label: 'name', value: 'code', children: 'children' },
                    options: getSelectorData('IndicatorExternal', 'Cascader'),
                    onChange(value, selectOptions) {
                      // console.log({ value, selectOptions });

                      var nodes: any[] = [];

                      function parseTreeJson(array: any[]) {
                        if (!array) return [];
                        for (let index = 0; index < array.length; index++) {
                          const element = array[index];
                          // 判断element.children是对象
                          if (element.children && typeof element.children == 'object') {
                            parseTreeJson(element.children);
                          } else {
                            // 判断是否为子节点
                            if (!(element.children || typeof element.children == 'object')) {
                              // 获得符合的 node
                              nodes.push(element);
                            }
                          }
                        }
                      }

                      if (value.length > 0) {
                        for (let index = 0; index < value.length; index++) {
                          let current = value[index];
                          let key = current[current.length - 1];
                          const result = selectOptions[index].filter((t: any) => t.code == key);
                          console.log({ result });
                          if (result[0].children) {
                            //非直接叶子节点
                            parseTreeJson(result[0].children);
                          }
                          if (!result[0].children) {
                            //直接叶子节点
                            nodes.push({ code: result[0].code });
                          }
                        }
                      }

                      const codes = nodes.map((t) => t.code);
                      manaInfoformRef.current?.setFieldsValue({ _indicatorExternalList: codes });
                    },
                  }}
                />
                {/* <ProFormText colProps={{ md: 12, xl: 8 }} name="remark" label="其他备注" placeholder="请输入" /> */}
                <ProFormTextArea
                  colProps={{ md: 12, xl: 8 }}
                  name="remark"
                  label="其他备注"
                  placeholder="请输入"
                  fieldProps={{
                    allowClear: true,
                    autoSize: true,
                    size: 'small',
                  }}
                />
              </ProForm>
            </div>
          </div>

          <div className="card">
            <div className="cardTitle">指标展示设定</div>
            <div className="formContent">
              <ProForm
                formRef={showSetInfoformRef}
                layout={'vertical'}
                grid={true}
                autoFocusFirstInput={false}
                rowProps={{
                  gutter: [16, 0],
                }}
                initialValues={
                  renderType == 'ADD'
                    ? {}
                    : renderType == 'EDIT' && record
                    ? {
                        ...record,
                        caseBreakdown: record.caseBreakdown ? record.caseBreakdown.split('/') : [],
                        chartType: record.chartType ? record.chartType.split('/') : [],
                        dataDownload: record.dataDownload ? record.dataDownload.split('/') : [],
                        dataSum: record.dataSum ? record.dataSum.split('/') : [],
                        drillLevel: record.drillLevel ? record.drillLevel.split('/') : [],
                      }
                    : {}
                }
                submitter={{
                  render: () => null,
                }}
              >
                <ProFormSelect
                  colProps={{ md: 12, xl: 8 }}
                  name="appearDate"
                  label="呈现期间"
                  fieldProps={{ size: 'small' }}
                  options={[
                    {
                      label: '年',
                      value: '年',
                    },
                    {
                      label: '季',
                      value: '季',
                    },
                    {
                      label: '月',
                      value: '月',
                    },
                  ]}
                  placeholder="请选择"
                />
                <ProFormSelect
                  colProps={{ md: 12, xl: 8 }}
                  name="chartType"
                  label="图表形态"
                  fieldProps={{
                    size: 'small',
                    mode: 'multiple',
                    maxTagCount: 'responsive',
                  }}
                  options={[
                    {
                      label: '统计表',
                      value: '统计表',
                    },
                    {
                      label: '直方图',
                      value: '直方图',
                    },
                    {
                      label: '趋势图',
                      value: '趋势图',
                    },
                    {
                      label: '其他',
                      value: '其他',
                    },
                  ]}
                  placeholder="请选择"
                />
                <ProFormSelect
                  colProps={{ md: 12, xl: 8 }}
                  name="dataSum"
                  label="数据汇总呈现"
                  fieldProps={{
                    size: 'small',
                    mode: 'multiple',
                    maxTagCount: 'responsive',
                  }}
                  options={[
                    { label: '全院', value: '全院' },
                    { label: '分院', value: '分院' },
                  ]}
                  placeholder="请选择"
                />

                <ProFormSelect
                  colProps={{ md: 12, xl: 8 }}
                  name="drillLevel"
                  label="资料下钻层级"
                  fieldProps={{
                    size: 'small',
                    mode: 'multiple',
                    maxTagCount: 'responsive',
                  }}
                  options={[
                    {
                      label: '全院',
                      value: '全院',
                    },
                    {
                      label: '分院区',
                      value: '分院区',
                    },
                    {
                      label: '科别',
                      value: '科别',
                    },
                    {
                      label: '医师别',
                      value: '医师别',
                    },
                    {
                      label: '个案',
                      value: '个案',
                    },
                  ]}
                  placeholder="请选择"
                />
                <ProFormSelect
                  colProps={{ md: 12, xl: 8 }}
                  name="dataDownload"
                  label="资料下载"
                  fieldProps={{
                    size: 'small',
                    mode: 'multiple',
                    maxTagCount: 'responsive',
                  }}
                  options={[
                    {
                      label: '全院',
                      value: '全院',
                    },
                    {
                      label: '分院区',
                      value: '分院区',
                    },
                    {
                      label: '科别',
                      value: '科别',
                    },
                    {
                      label: '医师别',
                      value: '医师别',
                    },
                    {
                      label: '个案数',
                      value: '个案数',
                    },
                  ]}
                  placeholder="请选择"
                />
                <ProFormSelect
                  colProps={{ md: 12, xl: 8 }}
                  name="caseBreakdown"
                  label="个案明细字段"
                  fieldProps={{
                    size: 'small',
                    mode: 'multiple',
                    maxTagCount: 'responsive',
                  }}
                  options={[
                    {
                      label: '看诊科别',
                      value: '看诊科别',
                    },
                    {
                      label: '就诊日期',
                      value: '就诊日期',
                    },
                    {
                      label: '住院科别',
                      value: '住院科别',
                    },
                    {
                      label: '出院科别',
                      value: '出院科别',
                    },
                    {
                      label: '病历号',
                      value: '病历号',
                    },
                    {
                      label: '住院日期时间',
                      value: '住院日期时间',
                    },
                    {
                      label: '转出日期',
                      value: '转出日期',
                    },
                    {
                      label: '出院日期时间',
                      value: '出院日期时间',
                    },
                    {
                      label: '出院类别',
                      value: '出院类别',
                    },
                    {
                      label: '出院诊断码',
                      value: '出院诊断码',
                    },
                    {
                      label: '合并症码',
                      value: '合并症码',
                    },
                    {
                      label: '死亡原因',
                      value: '死亡原因',
                    },
                    {
                      label: '手术代码',
                      value: '手术代码',
                    },
                    {
                      label: '其他',
                      value: '其他',
                    },
                  ]}
                  placeholder="请选择"
                />
              </ProForm>
            </div>
          </div>

          <div className="card">
            <div className="cardTitle">管理员维护信息</div>
            <div className="formContent">
              <ProForm
                formRef={adminInfoformRef}
                layout={'vertical'}
                grid={true}
                autoFocusFirstInput={false}
                initialValues={
                  renderType == 'ADD'
                    ? { isPublic: 1 }
                    : renderType == 'EDIT' && record
                    ? {
                        ...record,
                        indicatorMenuList: setFormInit('indicatorMenuList'),
                      }
                    : {}
                }
                rowProps={{
                  gutter: [16, 0],
                }}
                submitter={{
                  render: () => null,
                }}
              >
                <ProFormCascader
                  colProps={{ md: 12, xl: 8 }}
                  name="indicatorMenuList"
                  label="指标目录"
                  rules={[{ required: true, message: '这是必填项' }]}
                  fieldProps={{
                    size: 'small',
                    multiple: true,
                    fieldNames: { label: 'name', value: 'code' },
                    onChange(value: any, selectOptions: any) {
                      console.log({ value, selectOptions });

                      var nodes: any[] = [];

                      function parseTreeJson(array: any[]) {
                        if (!array) return [];
                        for (let index = 0; index < array.length; index++) {
                          const element = array[index];
                          // 判断element.children是对象
                          if (element.children && typeof element.children == 'object') {
                            parseTreeJson(element.children);
                          } else {
                            // 判断是否为子节点
                            if (!(element.children || typeof element.children == 'object')) {
                              // 获得符合的 node
                              nodes.push(element);
                            }
                          }
                        }
                      }

                      if (value.length > 0) {
                        for (let index = 0; index < value.length; index++) {
                          let current = value[index];
                          let key = current[current.length - 1];
                          const result = selectOptions[index].filter((t: any) => t.code == key);
                          // console.log({result});
                          if (result[0].children) {
                            //非直接叶子节点
                            parseTreeJson(result[0].children);
                          }
                          if (!result[0].children) {
                            //直接叶子节点
                            nodes.push({ code: result[0].code });
                          }
                        }
                      }

                      const codes = nodes.map((t) => t.code);
                      console.log({ codes, nodes });
                      adminInfoformRef.current?.setFieldsValue({ _indicatorMenuList: codes });
                    },
                  }}
                  request={async () => {
                    if (location.search.length > 0) {
                      const id = location.search.split('=')[1];
                      if (id) {
                        const dirData = await getIndicatorDictionary();
                        if (dirData) {
                          const result = dirData.filter((t) => t.code == id);

                          if (result.length > 0) {
                            return result[0].children;
                          }
                        }
                        return [];
                      }
                    }

                    return [];
                  }}
                  placeholder="请选择"
                />

                <ProFormSelect
                  colProps={{ md: 12, xl: 8 }}
                  name="isPublic"
                  label="是否公开"
                  fieldProps={{ size: 'small' }}
                  options={[
                    {
                      label: '是',
                      value: 1,
                    },
                    {
                      label: '否',
                      value: 0,
                    },
                  ]}
                  placeholder="请选择"
                />
                <ProFormSelect
                  colProps={{ md: 12, xl: 8 }}
                  name="version"
                  label="版本"
                  fieldProps={{ size: 'small' }}
                  options={[
                    {
                      label: '版本1',
                      value: 1,
                    },
                    {
                      label: '版本2',
                      value: 2,
                    },
                    {
                      label: '版本3',
                      value: 3,
                    },
                  ]}
                  placeholder="请选择"
                />
              </ProForm>
            </div>
          </div>
        </div>
      </Drawer>
    </div>
  );
};

export default DrawerForm;
