import React, { useEffect, useRef, useState } from "react";
import { type ProColumns, type ActionType, type ProFormInstance, ProTable, EditableProTable } from '@ant-design/pro-components';
import type {FormInstance} from 'antd'
import  {Upload} from 'antd'
import { SDPage,SDFormText,SDModalForm,SDTable,SDFormItem,SDButton,SDSubmitButton,EditType, SDAreaTtile, SDOperate, baseFun,SDModal, validateFun, SDLayout, SDFormDict, } from "@sundata/ui-frame";
import type { SupplementTaskDefineModel,SupplementTemplateRelationModel,TemplateDataValidationRuleModel, } from '@/services/rwa/product/datasupplementary/supplementtaskmanagement';
import {getDataList,selectDetailData,getTemplateCheckDataList,getTemplateDataList,deleteInfoData,updateRowData,isNotExist,
  createRowData,createTemplateListRowData,createTemplateCheckRowData,selectDict,selectDictDefine,getNextId} from '@/services/rwa/product/datasupplementary/supplementtaskmanagement';
import { PlusSquareTwoTone, WomanOutlined } from "@ant-design/icons";
import { ProductProps } from "@/sundataImport";
import { toNumber } from "lodash";
import { useModel } from '@umijs/max';
import { countChineseChars } from "@/services/rwa/product/rwacheckutils";
import { DictTree } from "@sundata/ui-frame/es/types";

type widowRush = {
  onCancel:  () => void;
  onChangeVisible(visible: boolean, type: string): unknown;
  onChangeVisdible:(visible:boolean,type ?: 'none' | 'raload' )=>void;
}& ProductProps;
const supplementtaskmanagement : React.FC<widowRush> = (prop:widowRush) => {

    /** 编辑方式，查看、修改、新增按钮时设置，详细信息表单中使用 */
    const [editType, setEditType] = useState<EditType>(prop.editType || 'display');
    /** 是否显示详细信息窗口 */
    const [detailVisible, setDetailVisible] = useState<boolean>(false);
    /** 是否excel公式字段是否必输 */
    const [excelFormulaFlag, setExcelFormulaFlag] = useState<boolean>(false);
    const [sqlCode,setSqlCode] = useState<boolean>(false);
    const [dateType,setDateType] = useState<boolean>(false);
    const [currentRow, setCurrentRow] = useState<SupplementTaskDefineModel>();
    /** 表格引用对象，刷新表格使用   */
    const actionRef = useRef<ActionType>();
    const formRef = useRef<FormInstance<any>>();
    const templateListRef = useRef<FormInstance<any>>();
    const templateCheckRef = useRef<FormInstance<any>>();
    const templateListActionRef = useRef<ActionType>();
    const templateCheckActionRef = useRef<ActionType>();

    const [templateListData, setTemplateListData] = useState<SupplementTemplateRelationModel[]>();
    const [templateCheckData, setTemplateCheckData] = useState<TemplateDataValidationRuleModel[]>();
    // 页面数据
    var formDataList = new Array<TemplateDataValidationRuleModel>;

    const [dictionArray1,setDictionArray1] = useState<any[]>();
    const [dictionArray2,setDictionArray2] = useState<any[]>();

    // 字典
    const { fetchDict } = useModel('dict');
    const [account,setAccount] = useState <any>();

    /** 字段关系序号编辑 */
    var dataInfoIndex = 0;

    useEffect(() => {
      selectDict().then((data)=>{
        setDictionArray1(data);
      });
      selectDictDefine().then((data)=>{
        setDictionArray2(data);
      });
      }, []);
    
    // 修改查询查询
    const selectData = async (formdata : SupplementTaskDefineModel) => {
      const data = await selectDetailData(formdata);
      formRef.current?.setFieldsValue(data);
      const dataList = await getTemplateDataList(formdata);
      setTemplateListData(dataList);
      const templateList = await getTemplateCheckDataList(formdata);
      setTemplateCheckData(templateList);
     }

     // 删除
    const deleteData = async(formdata : SupplementTaskDefineModel) => {
      baseFun.confirm('请确认是否继续操作？',async() =>{
        await deleteInfoData(formdata);
        baseFun.info("删除成功");
        closeAndRefresh();
       });
    }



    // 插入或者更新数据
  const handleSave = async(data: SupplementTaskDefineModel,) => {
    if (editType == 'update' ) {
      const updateRes = await updateRowData(data);
      if (updateRes == true) {
        if (templateListData && templateCheckData) {
          if (templateListData.length >= 1) {
            const res01 = await createTemplateListRowData(templateListData,data.taskCode);
            if ( res01 == true) {
               const res02 = await createTemplateCheckRowData(templateCheckData);
               if (res02 == true) {
                closeAndRefresh();
               }
            }
          } else {
            baseFun.error('补录数据模板列表至少有一条记录');
          }
        }
      }
    } else if (editType == 'create' ) {
      const createRes= await createRowData(data);
      if (createRes == true) {
        if (templateListData && templateCheckData) {
          const res01 = await createTemplateListRowData(templateListData,data.taskCode);
          if ( res01 == true) {
            const res02 = await createTemplateCheckRowData(templateCheckData);
            if (res02 == true) {
              closeAndRefresh();
             }
          } else {
             baseFun.error('补录数据模板列表至少有一条记录');
          }
        }
      }
    }
    setDetailVisible(false);
  }


    //关闭窗口刷新父页面
    const closeAndRefresh = ()=>{
    actionRef.current?.reloadAndRest?.();
    }


     
    // 数据补录模板定义
    const columns: ProColumns<SupplementTaskDefineModel>[] = [
        {
          title: '序号',
          dataIndex: 'index',
          search: false,
          render: (text, record, index) => { index  = index + 1;return index},
          width:100,
          ellipsis:true
        },
        {
          title: '计算实例号',
          dataIndex: 'calcIndex',
          search: false,
          hideInTable: true,
        },
        {
          title: '起始数据日期',
          dataIndex: 'startDate',
          search: false,
          hideInTable: true,
        },
        {
          title: '截止数据日期',
          dataIndex: 'endDate',
          search: false,
          hideInTable: true,
        },
        {
          title: '期次',
          dataIndex: 'term',
          search: false,
          hideInTable: true,
        },
        {
          title: '任务编号', 
          dataIndex: 'taskCode',
          hideInTable: false,
        },
        {
          title: '任务名称', 
          dataIndex: 'taskName',
          hideInTable: false,
        },
        {
          title: '负责机构', 
          dataIndex: 'orgCodes',
          valueType:"treeSelect",
          request:()=>fetchDict("org"),
          fieldProps:{ 
            reeDefaultExpandAll:true,
            treeCheckable:true, 
           popupMatchSelectWidth:300 
          },
          hideInTable: true,
        },
        {
          title: '负责机构', 
          dataIndex: 'orgCode',
          valueType:"treeSelect",
          search:false,
          request:()=>fetchDict("org"),
          hideInTable: false,
        },
        {
          title: '首选负责人', 
          dataIndex: 'account',
          valueType:'select',
          request:()=>fetchDict({dictKey :'@account2'  }),
          hideInTable: false,
          search: false,
        },
        {
          title: '补录频率', 
          dataIndex: 'frequencys',
          valueType:'treeSelect',
          request:()=>fetchDict('FREQUENCY'),
           fieldProps: {
              treeDefaultExpandAll: true,
              treeCheckable:true,
            },
          hideInTable: true,
          //search: false,
        },
        {
          title: '补录频率', 
          dataIndex: 'frequency',
          valueType:'select',
          request:()=>fetchDict('FREQUENCY'),
          hideInTable: false,
          search: false,
        },
        {
          title: '天数调整', 
          dataIndex: 'adjustment',
          hideInTable: false,
          search: false,
        },
        {
          title: '模板编号', 
          dataIndex: 'tmpCode',
          hideInTable: true,
      //    search: false,
        },
        {
          title: '模板名称', 
          dataIndex: 'tmpNames',
          hideInTable: true,
      //    search: false,
        },
        {
          title: '包含模板', 
          dataIndex: 'tmpNames',
          hideInTable: false,
          search: false,
        },
        {
          title: '状态', 
          dataIndex: 'status',
          hideInTable: false,
          search: false,
        },
        {
          title: '操作',
          dataIndex: 'operate',
          valueType: 'option',
          render: (_, record) => [
            <SDOperate
              key="roleCfg"
              icon={<WomanOutlined />}
              successMessage=""
              onClick={
                ()=>{ 
                selectData(record);
                setDetailVisible(true);
                setEditType('update');
                setAccount(record.orgCode)
               } }
            >
              修改
            </SDOperate>,
            <SDOperate
            key="roleCfg"
            icon={<WomanOutlined />}
            successMessage=""
            onClick={
              ()=>{ 
              deleteData(record);
             } }
          >
            作废
          </SDOperate>,
            <SDOperate
            key="roleCfg"
            icon={<WomanOutlined />}
            successMessage=""
            onClick={
              ()=>{ 
              selectData(record);
              setDetailVisible(true);
              setEditType('update');
             } }
          >
            查看
          </SDOperate>,
           
          ],
        },
      ];

       // 补录模板列表
       const templateListColumns: ProColumns<SupplementTemplateRelationModel>[] = [
        {
          title: '序号',
          dataIndex: 'id',
          search: false,
          render: (text, record, index) => { index  = index + 1; return index},
          width:100,
          ellipsis:true,
          editable:false
        },
          {
            title: '计算实例号',
            dataIndex: 'calcIndex',
            search: false,
            hideInTable: true,
          },
          {
            title: '起始数据日期',
            dataIndex: 'startDate',
            search: false,
            hideInTable: true,
          },
          {
            title: '截止数据日期',
            dataIndex: 'endDate',
            search: false,
            hideInTable: true,
          },
          {
            title: '期次',
            dataIndex: 'term',
            search: false,
            hideInTable: true,
          },
          {
            title: '补录模板',
            dataIndex: 'tmpCodeOfDefine',
            search: false,
            hideInTable: false,
            valueType:'treeSelect',
         //   request:()=>fetchDict({ dictKey : '@tmpCode'}),
            formItemProps:{
              rules:[
                {required:true},
                {validator:(rules,value,callback)=>{
                  if (templateListData?.find(item => value === item?.tmpCodeOfDefine)) {
                    callback('补录模板列表不可出现重复模板');
                  } else if (value === '请选择补录模板'){
                    callback('请选择补录模板');
                  } else {
                    callback();
                  }
                }},
              ]
            },
            fieldProps: {
              options: dictionArray2,
            }
          },
          {
            title: '补录模板说明',
            dataIndex: 'remark',
            search: false,
            hideInTable: false,
            formItemProps:{
              rules:[
                {validator:(rules,value,callback)=>{
                  let chineseCount = countChineseChars(value);
                  if (chineseCount > 200) {
                      callback('最多200个汉字');
                  } else if (chineseCount<=0) {
                      callback('请输入补录模板说明(汉字)');
                  } else{
                    callback();
                  }
               }},]
            }
          },
          {
            title: '数据初始化逻辑', 
            dataIndex: 'sqlCode',
            search: false,
            hideInTable: false,
            formItemProps:{
              rules:[
                {required:true},]
            }
          },
          {
            title: '操作',
            dataIndex: 'operate',
            valueType: 'option',
            render: (_, record) => [
              <SDOperate
                key="roleCfg"
                icon={<WomanOutlined />}
                successMessage=""
                onClick={async ()=>{
                  templateListActionRef.current?.startEditable(record.tmpCodeOfDefine);
                 } }
              >
                编辑
              </SDOperate>,
            ],
          },
        ];


       // 补录模板校验规则
       const templateCheckColumns: ProColumns<TemplateDataValidationRuleModel>[] = [
          {
            title: '序号',
            dataIndex: 'id',
            search: false,
            render: (text, record, index) => { index  = index + 1;return index},
            width:100,
            ellipsis:true,
            editable:false
          },
          {
            title: '计算实例号',
            dataIndex: 'calcIndex',
            search: false,
            hideInTable: true,
            width:150,
            ellipsis:true
          },
          {
            title: '起始数据日期',
            dataIndex: 'startDate',
            search: false,
            hideInTable: true,
            width:150,
            ellipsis:true
          },
          {
            title: '截止数据日期',
            dataIndex: 'endDate',
            search: false,
            hideInTable: true,
            width:150,
            ellipsis:true
          },
          {
            title: '期次',
            dataIndex: 'term',
            search: false,
            hideInTable: true,
            width:150,
            ellipsis:true
          },
          {
            title: '规则编号',
            dataIndex: 'tmpverificationCode',
            search: false,
            width:100,
            ellipsis:true,
            hideInTable:true,
            editable:false
          },
          {
            title: '规则名称',
            dataIndex: 'tmpverificationName',
            hideInTable: false,
            width:150,
            ellipsis:true,
            formItemProps:{
              rules:[
                {validator:(rules,value,callback)=>{
                  let chineseCount = countChineseChars(value);
                  if (chineseCount > 100) {
                      callback('最多100个汉字');
                  } else if (chineseCount<=0) {
                      callback('请输入规则名称(汉字)');
                  } else{
                    callback();
                  }
               }},]
            }
          },
          {
            title: '补录模板',
            dataIndex: 'tmpCode',
            hideInTable: false,
            width:150,
            ellipsis:true,
            valueType:'treeSelect',
            formItemProps:{
              rules:[
                {required:true},]
            },
            fieldProps: {
              options: dictionArray1,
            }
          },
          {
            title: '行列类型', 
            dataIndex: 'tmpverRowColType',
            hideInTable: false,
            valueType:'select',
            request:()=>fetchDict({ dictKey :'ROW_COLUMN_TYPE'}),
            width:150,
            ellipsis:true,
            formItemProps:{
              rules:[
                {required:true},]
            }
          },
          {
            title: '模板验证时点', 
            dataIndex: 'vartimmer',
            hideInTable: false,
            width:150,
            ellipsis:true,
            valueType: 'treeSelect',
            request: () => fetchDict('TEMPLATE_VERIFY_TIME'),
            fieldProps: {
            treeDefaultExpandAll: true,
            },
            formItemProps:{
              rules:[
                {required:true},]
            }
          },
          {
            title: '行范围', 
            dataIndex: 'tmpverRowRange',
            hideInTable: false,
            width:150,
            ellipsis:true,
            formItemProps:{
              rules:[
                {pattern: RegExp(`[0-9]+\\-[0-9]+|[n|N]`),message:'请输入正确范围'},
                {required:true},
              ]
            }
          },
          {
            title: '列范围', 
            dataIndex: 'tmpverColumnRange',
            hideInTable: false,
            width:150,
            ellipsis:true,
            formItemProps:{
              rules:[
                {pattern: RegExp(`[0-9]+\\-[0-9]+|[n|N]`),message:'请输入正确范围'},
                {required:true},
              ]
            }
          },
          {
            title: '约束方式', 
            dataIndex: 'checkType',
            hideInTable: false,
            width:150,
            ellipsis:true,
            valueType: 'treeSelect',
            request: () => fetchDict('CONSTRAINT_METHOD'),
            fieldProps: {
            treeDefaultExpandAll: true,
            },
            formItemProps:{
              rules:[
                {required:true},]
            },
          },
          {
            title: '数据类型', 
            dataIndex: 'dataType',
            hideInTable: false,
            width:150,
            ellipsis:true,
            formItemProps:{
              rules:[
                {required:excelFormulaFlag},]
            }
          },
          {
            title: '约束公式', 
            dataIndex: 'excelFormula',
            hideInTable: false,
            width:150,
            ellipsis:true,
            formItemProps:{
              rules:[
                {required:excelFormulaFlag},]
            }
          },
          {
            title: '约束规则SQL', 
            dataIndex: 'sqlCode',
            hideInTable: false,
            width:150,
            ellipsis:true,
            formItemProps:{
              rules:[
                {required:sqlCode},]
            }
          },
          {
            title: '越界处理方式', 
            dataIndex: 'exceedType',
            hideInTable: false,
            width:150,
            ellipsis:true,
            valueType: 'treeSelect',
            request: () => fetchDict('CROSS_BORDER_DISPOSAL'),
            fieldProps: {
            treeDefaultExpandAll: true,
            },
            formItemProps:{
              rules:[
                {required:true},]
            }
          },
          {
            title: '提示信息模板', 
            dataIndex: 'errorMsgTmplate',
            hideInTable: false,
            width:150,
          ellipsis:true
          },
          {
            title: '操作',
            dataIndex: 'operate',
            valueType: 'option',
            width:150,
          ellipsis:true,
            render: (_, record) => [
              <SDOperate
                key="roleCfg"
                icon={<WomanOutlined />}
                successMessage=""
                onClick={
                  async()=>{ 
                  templateCheckActionRef.current?.startEditable(record.tmpverificationCode);
                 }}
              >
                编辑
              </SDOperate>,
            ],
          },
        ];
        
        
    
    return (
        <SDPage>
        <SDTable
         title="查询表格"
         rowKey="customerName"
         request={async (formdata:SupplementTaskDefineModel) =>{
           const formDatas = await getDataList(formdata);
           return {data: formDatas}
         }  }
         columns={columns}
         toolBarRender={(_, { selectedRows }) => [
          <SDButton
            key="export"
            icon={<PlusSquareTwoTone/>}
            successMessage=''
            onClick={() => {
                setEditType('create');
                setDetailVisible(true);
                setTemplateListData([]);
                setTemplateCheckData([]);
            }}
          >
            新增
          </SDButton>,
        ]}
         actionRef={actionRef}
         formRef={formRef}
         setDetailVisible={() => {setDetailVisible(true)}}
         setEditType={setEditType}
         setCurrentRow={setCurrentRow}
         />

        {detailVisible && (
        <SDModalForm
          title={'详细信息'}
          editType={editType}
          params={currentRow}
          visible={detailVisible}
          onVisibleChange={() => {setDetailVisible(false)}}
          onValuesChange={(changedValues,values)=>{
            if(values.orgCode!=''||values.orgCode!=undefined){
              setAccount(values.orgCode);
              
            }
          }
          }
          footer={[
            <SDSubmitButton  editType={editType}   formRef={formRef} doSubmit={handleSave} >保存</SDSubmitButton>,
            <SDButton
              key="closeUpdate"
              successMessage=''
              onClick={() => {
                 setDetailVisible(false);
              }}>关闭</SDButton>
            ]}
          tableRef={actionRef}
          formRef={formRef}
        >
            <SDAreaTtile title='补录任务新增页面'/>
            <SDFormText name="taskCode"      readonlyCond="update" required={true} rules={[{max:60,message:'最多60个字符'}]}
             bgValidater={(taskCode: string) => isNotExist({
               taskCode: taskCode,
               taskName: "",
             })}
            label="任务编号"/>
            <SDFormText name="taskName"  rules={[{validator:(rules,value,callback)=>{
            let chineseCount = countChineseChars(value);
            if (chineseCount > 100) {
                callback('最多100个汉字');
            } else if (chineseCount<=0) {
                callback('请输入汉字');
            } else{
              callback();
            }
         }}]}   label="任务名称"/>
            <SDFormDict dictKey="org"  name="orgCode"      label="责任机构"/>
            <SDFormDict dictKey="@account1" name="account"     label="首选责任人" dictParam={`{"account":"${account}"}`}/>
            <SDFormDict dictKey="FREQUENCY" name="frequency"  label="补录频率"/>
            <SDFormText name="adjustment"  label="天数调整"/>
            <SDFormDict dictKey="@tmpFileCode" name="tmpFileCode"  label="所属阶段" />
        <SDLayout>
        <SDAreaTtile title='补录模板列表'/>
        <EditableProTable
              rowKey="tmpCodeOfDefine"
              columns={templateListColumns}
              recordCreatorProps={false}
              actionRef={templateListActionRef}
              value={templateListData}
              editable={{
                actionRender: (row,config,defaultDoms)=>{
                  return [defaultDoms.save,defaultDoms.delete,defaultDoms.cancel]
                },
              }}
              toolBarRender={(_, { selectedRowKeys }) => editType == 'create' || editType == 'update' ? [
                <SDButton
                  key="export"
                  successMessage=''
                  onClick={() => {
                    templateListActionRef.current?.addEditRecord?.({
                      tmpCodeOfDefine: '请选择补录模板',
                      title: 'NEWROW',
                    });
                  }}
                >
                  新增
                </SDButton>,
              ]:[]}
              onChange={ (value: readonly SupplementTemplateRelationModel[]) => {
                setTemplateListData([...value]);
                // 判断array2中是否包含array1中的对象，并返回该对象的数组形式
                let foundObject = templateCheckData?.filter(obj1 => value?.find(obj2 => 
                obj2.tmpCodeOfDefine === obj1.tmpCode));
                if (foundObject) {
                  setTemplateCheckData([...foundObject]);
                }
                // 补录模板内新增一条数据（模板是新的）补录模板校验规则的补录模板下拉列表应实时更新
                // 先将补录模板校验规则的补录模板下拉列表清空
                dictionArray1?.splice(0,dictionArray1.length);
                // 遍历补录模板列表。将新出现的模板用temcode在dictionArray2下拉列表的数组中找到相应对象并压进dictionArray1里
                value?.forEach((item)=>{
                   const obj = dictionArray2?.find(e => e.value === item.tmpCodeOfDefine);
                   if (!dictionArray1?.includes(obj)){
                     dictionArray1?.push(obj);
                   }
                })
              }}
           />
        </SDLayout>

        <SDLayout>
        <SDAreaTtile title='补录模板校验规则'/>
        <EditableProTable
              rowKey="tmpverificationCode"
              columns={templateCheckColumns}
              recordCreatorProps={false}
              actionRef={templateCheckActionRef}
              scroll={{ x: 1500 }}
              value={templateCheckData}
              editable={{
                onValuesChange(value) {
                  if (value?.checkType) {
                    if (value.checkType == 'EXCEL_FORMULA') {
                      setExcelFormulaFlag(true);
                      setExcelFormulaFlag(false);
                      setDateType(false);
                    } else if (value.checkType == 'SQL_STATEMENT') {
                      setSqlCode(true);
                      setExcelFormulaFlag(false);
                      setDateType(false);
                    }else if(value.checkType == 'DATA_TYPE'){
                      setDateType(true);
                      setSqlCode(false);
                      setExcelFormulaFlag(false);
                    }  else {
                      setSqlCode(false);
                      setExcelFormulaFlag(false);
                    }
                  }
                },
                actionRender: (row,config,defaultDoms)=>{
                  return [defaultDoms.save,defaultDoms.delete,defaultDoms.cancel]
                }
              }}
              toolBarRender={(_, { selectedRowKeys }) => editType == 'create' || editType == 'update' ? [
                <SDButton
                  key="export"
                  successMessage=''
                  onClick={ async () => {
                    let nextId = await getNextId();
                    templateCheckActionRef.current?.addEditRecord?.({
                      tmpverificationCode: nextId,
                      title: 'NEWROW',
                    });
                  }}
                >
                  新增
                </SDButton>,
              ]:[]}
              onChange={ (value: readonly TemplateDataValidationRuleModel[]) => {
                setTemplateCheckData([...value]);
              } }
           />
        </SDLayout>
        </SDModalForm>
      )}


        </SDPage>
        
    );
}
export default supplementtaskmanagement;