import React, {FC, useRef, useState} from "react";
import {
  baseFun,
  EditType, SDAreaTtile,
  SDButton, SDEditableTable, SDFormDict,
  SDFormText,
  SDLayout,
  SDModalForm,
  SDOperate,
  SDPage,
  SDTable,
  SDTabs, validateFun
} from "@sundata/ui-frame";
import {
  deleteService, deleteServiceRules,
  getDataListService, getDataListServiceRules,
  getDetailByIdService, getDetailByIdServiceRules,
  insertService, insertServiceRules,
  RuleModel, RulesModel, testServiceRules, updateService, updateServiceRules
} from "@/services/internalEvaluation/configuration/Rule";
import {ProColumns} from "@ant-design/pro-table";
import {WomanOutlined} from "@ant-design/icons";
import {FormInstance} from "antd/lib/form";
import {ActionType} from "@ant-design/pro-components";
import {Popconfirm} from "antd";
import {useModel} from "@@/exports";
import {firstCharIsNotNumber} from "@/pages/internalEvaluation/utils/rwacheckutils";


const RulePage: FC = () => {

  const {fetchDict} = useModel('dict');

  const ruleIndexColumns: ProColumns<any>[] = [
    {
      title: '模板参数',
      dataIndex: 'ruleLogicParam',
      hideInTable: false,
      formItemProps:{
        wrapperCol:{ span: 16 },
        rules: [
          { required: true, message: '请输入模板参数' },
          {
            validator:validateFun.account
          },
          {
            validator: (rule, value, callback)=> {
              if (firstCharIsNotNumber(value)>0) {
                callback('模板参数不能以数字开头');
              } else {
                callback();
              }

            }
          }
        ],
      }
    },
    {
      title: '指标',
      dataIndex: 'indexNo',
      hideInTable: false,
      valueType:'select',
      request:()=>fetchDict('@selectAllIndexToDict'),
      formItemProps:{
        style: {width: '100%'},
        wrapperCol:{ span: 16 },
        required: true,
         rules: [{ required: true, message: '请选择指标信息' }],
      }
    }
  ]

  // 规则表格列信息
  const ruleColumns: ProColumns<RuleModel>[] = [
    {
      title: '所属规则集',
      dataIndex: 'rulesNo',
      hideInTable: true,
      valueType:'select',
      request:()=> fetchDict('@selectRulesToDictContent')
    },
    {
      title: '规则编号',
      dataIndex: 'ruleNo',
      hideInTable: false,
    },
    {
      title: '规则名称',
      dataIndex: 'ruleName',
      hideInTable: false,
    },
    {
      title: '规则阈值',
      dataIndex: 'ruleThreshold',
      search: false,
      hideInTable: false,
    },
    {
      title: '规则结果',
      dataIndex: 'ruleResult',
      hideInTable: false,
      search:false,
      valueType:'select',
      request:()=> fetchDict('RULE_RESULT_TYPE')
      // valueEnum: {
      //   'none': '无',
      //   'warn': '预警',
      //   'intercept': '拦截',
      // },
    },
    {
      title: '操作',
      dataIndex: 'operate',
      valueType: 'option',
      render: (_, record) => [
        <SDOperate
          key="rule-show"
          icon={<WomanOutlined/>}
          successMessage=""
          onClick={
            () => {
              openRuleModelForm();
              selectRuleDetail(record)
              setRuleEditType('display')
            }
          }
        >
          查看
        </SDOperate>,
        <SDOperate
          key="rule-edit"
          icon={<WomanOutlined/>}
          successMessage=""
          onClick={
            () => {
              openRuleModelForm();
              selectRuleDetail(record)
              setRuleEditType('update')
            }
          }
        >
          修改
        </SDOperate>,
        <Popconfirm
          title={'警告'}
          description={'此操作是不可逆的，确认要删除数据吗？'}
          onConfirm={async () => {
            await deleteService(record);
            ruleActionRef.current?.reload();
          }}
        >
          <SDOperate
            key="rule-delete"
            icon={<WomanOutlined/>}
            successMessage=""
          >
            删除
          </SDOperate>,
        </Popconfirm>
      ]
    }
  ]
  // 规则集表格列信息
  const rulesColumns: ProColumns<RulesModel>[] = [
    {
      title: '规则集编号',
      dataIndex: 'rulesNo',
      hideInTable: false,
    },
    {
      title: '规则集名称',
      dataIndex: 'rulesName',
      hideInTable: false,
    },
    {
      title: '规则集所属产品',
      dataIndex: 'belongProduct',
      hideInTable: false,
    },
    {
      title: '操作',
      dataIndex: 'operate',
      valueType: 'option',
      render: (_, record) => [
        <SDOperate
          key="rules-show"
          icon={<WomanOutlined/>}
          successMessage=""
          onClick={
            () => {

              openRulesModelForm();
              selectRulesDetail(record)
              setRulesEditType('display')
            }
          }
        >
          查看
        </SDOperate>,
        <SDOperate
          key="rules-edit"
          icon={<WomanOutlined/>}
          successMessage=""
          onClick={
            () => {
              openRulesModelForm();
              selectRulesDetail(record)
              setRulesEditType('update')
            }
          }
        >
          修改
        </SDOperate>,
        <Popconfirm
          title={'警告'}
          description={'此操作是不可逆的，确认要删除数据吗？'}
          onConfirm={async () => {
            await deleteServiceRules(record);
            rulesActionRef.current?.reload();
          }}
        >
          <SDOperate
            key="rules-delete"
            icon={<WomanOutlined/>}
            successMessage=""
          >
            删除
          </SDOperate>,
        </Popconfirm>,
        <SDOperate
          key="rules-edit"
          icon={<WomanOutlined/>}
          successMessage=""
          onClick={
            () => {
              console.log("规则集测试:", record);
              testRuleCalc(record);
            }
          }
        >
          测试
        </SDOperate>,
      ]
    }
  ]


  const testRuleCalc = async (record: RulesModel)=>{
    console.log(await testServiceRules(record).then(res=>{console.log(res)}))
  }

  const openRuleModelForm = ()=>{
    setRuleDetailVisible(true)
    setRuleIndexList([]);
  }

  const closeRuleModelForm = ()=>{
    setRuleDetailVisible(false)
  }

  const openRulesModelForm = ()=>{
    setRulesDetailVisible(true)
  }

  const closeRulesModelForm = ()=>{
    setRulesDetailVisible(false)
  }


  const saveOrUpdateInfo = async (re: RuleModel) => {
    re.ruleIndexList = ruleIndexList;
    const isSuccess = ruleEditType === 'create' ? await insertService(re) : await updateService(re) as boolean;
    if (isSuccess) {
      closeRuleModelForm();
      baseFun.info("操作成功")
    }
  }

  const saveOrUpdateInfoRules = async (re: RulesModel) => {
    const isSuccess = rulesEditType === 'create' ? await insertServiceRules(re) : await updateServiceRules(re) as boolean;
    if (isSuccess) {
      closeRulesModelForm();
      baseFun.info("操作成功")
    }
  }

  // 规则
  const selectRuleDetail = async (record: RuleModel) => {
    const res = await getDetailByIdService(record) as RuleModel ;
    setRuleIndexList(res.ruleIndexList);
    ruleFormRef.current?.setFieldsValue(res)
  }
  // 规则集
  const selectRulesDetail = async (record: RulesModel) => {
    // const res = await getDetailByIdServiceRules(record) as RulesModel ;
    // openRulesModelForm();
    // console.log(res)
    // rulesFormRef.current?.setFieldsValue(res)

    await getDetailByIdServiceRules(record).then((res)=>{
      rulesFormRef.current?.setFieldsValue(res);
    })


  }


  // hooks
  // 规则
  const [ruleDetailVisible, setRuleDetailVisible] = useState(false);
  const [ruleEditType, setRuleEditType] = useState<EditType>("display");
  const ruleFormRef = useRef<FormInstance<any>>();
  const ruleActionRef = useRef<ActionType>();
  const [ruleIndexList, setRuleIndexList] = useState<any>([]);
  // 规则集
  const [rulesDetailVisible, setRulesDetailVisible] = useState(false);
  const [rulesEditType, setRulesEditType] = useState<EditType>("display");
  const rulesFormRef = useRef<FormInstance<any>>();
  const rulesActionRef = useRef<ActionType>();

  // 规则
  const ruleMode = (
    <>
      <SDTable
        actionRef={ruleActionRef}
        title={'配置列表'}
        toolBarRender={
          () => [
            <SDButton
              key="rule-add"
              successMessage=""
              onClick={() => {
                openRuleModelForm()
                setRuleEditType('create')
              }}
            >
              新增
            </SDButton>,
          ]
        }
        rowKey={'ruleNo'}
        request={
          async (body: any) => {
            return {data: await getDataListService(body)}
          }
        }
        columns={ruleColumns}/>
      <SDModalForm
        tableRef={ruleActionRef}
        successMessage={''}
        doSubmit={re => saveOrUpdateInfo(re)}
        visible={ruleDetailVisible}
        onVisibleChange={setRuleDetailVisible}
        formRef={ruleFormRef}
        editType={ruleEditType}
      >
        <SDAreaTtile title={"基本信息"}/>
        <SDFormText label="规则编号" name="ruleNo" required={true}  width={'md'} readonlyCond={"update"}/>
        <SDFormText label="规则名称" name="ruleName"  width={'md'} required={true}/>
        <SDFormText label="规则模板" type={'textarea'} name="ruleTemplate" />
        <SDFormText label="模板说明" type={'textarea'} name="templateDesc" />
        <SDFormDict label="规则结果" name="ruleResult"  width={'md'} required={true} dictKey={'RULE_RESULT_TYPE'} />
        {/*<SDFormDict label="规则指标" multiple={true} dictKey={'@selectAllIndexToDict'} name="indexNoList"  width={'md'}/>*/}
        <SDFormText label="规则阈值" name="ruleThreshold"  width={'md'}/>
        <SDFormText label="规则结论" type={'textarea'} name="ruleConclusionTemplate" />
        <SDAreaTtile title={"指标清单"}/>
        {/*<SDButton onClick={()=>{*/}
        {/*  const str = ruleFormRef.current?.getFieldValue("ruleTemplate")*/}
        {/*  console.log(str)*/}
        {/*  // 提取所有 ${...} 格式的变量名*/}
        {/*  const variables = str.match(/\${(.*?)}/g)?.map((v: string) => v.replace(/\${|}/g, '')) || [];*/}
        {/*  console.log(variables)*/}

        {/*  // ruleLogicParam*/}
        {/*  // indexNo*/}

        {/*  var map = variables.map((v: string) => {*/}
        {/*    */}
        {/*    */}
        {/*    */}
        {/*    */}
        {/*  });*/}
        {/*  setRuleIndexList()*/}



        {/*}}>哈哈哈</SDButton>*/}
        <SDEditableTable

          columns={ruleIndexColumns} value={ruleIndexList} onChange={(value)=>{
          setRuleIndexList([...value])}}/>
      </SDModalForm>
    </>
  )
// 规则集
  const rulesMode = (
    <>
      <SDTable
        actionRef={rulesActionRef}
        title={'配置列表'}
        toolBarRender={
          () => [
            <SDButton
              key="rules-add"
              successMessage=""
              onClick={() => {
                openRulesModelForm()
                setRulesEditType('create')
              }}
            >
              新增
            </SDButton>,
          ]
        }
        rowKey={'rulesNo'}
        request={
          async (body: any) => {
            return {data: await getDataListServiceRules(body)}
          }
        }
        columns={rulesColumns}/>
      <SDModalForm
        tableRef={rulesActionRef}
        successMessage={''}
        doSubmit={re => saveOrUpdateInfoRules(re)}
        visible={rulesDetailVisible}
        onVisibleChange={setRulesDetailVisible}
        formRef={rulesFormRef}
        editType={rulesEditType}
      >
        <SDFormText label="规则集编号" name="rulesNo" required={true}  width={'md'} readonlyCond={"update"}/>
        <SDFormText label="规则集名称" name="rulesName"  width={'md'} required={true}/>
        <SDFormText label="规则集所属产品" name="belongProduct" required={true} />
        <SDFormText label="规则集结论" type={'textarea'} name="rulesConclusionTemplate" />
        <SDFormDict label="相关规则清单" name="ruleIds"  width={'md'} dictKey={'@selectRuleToDictContent'} multiple required={true} />
      </SDModalForm>
    </>
  )


  return (
    <SDPage>
      <SDLayout subLayout={'horizontal'}>
        <SDLayout
          title={'规则和规则集管理'}
          fixHeight={true}
        >
          <SDTabs items={[
            {
              key: 'rule',
              label: '规则配置',
              children: ruleMode,
            },
            {
              key: 'rules',
              label: '规则集配置',
              children: rulesMode,
            },
          ]}/>
        </SDLayout>
      </SDLayout>
    </SDPage>
  )
}


export default RulePage;
