import React, { useEffect, useRef, useState } from "react";
import { type ProColumns, type ActionType, type ProFormInstance, ProTable } from '@ant-design/pro-components';
import type {FormInstance,CollapseProps} from 'antd'
import  {Upload,Collapse} from 'antd'
import { SDPage,SDFormText,SDModalForm,SDTable,SDFormItem,SDButton,SDSubmitButton,EditType, SDAreaTtile, SDOperate, baseFun,SDModal, validateFun, SDFormDict, SDLayout, } from "@sundata/ui-frame";
import type { SysListModel,productListModel,subjectListModel } from '@/services/rwa/rwa_calc_config_dataparam/bussiness';
import {getDataList,selectDetailData,deleteRows,isNotExist,
  updateExistData,fetchDetailData,selectProductData,selectSubjectData} from '@/services/rwa/rwa_calc_config_dataparam/bussiness';
import { WomanOutlined } from "@ant-design/icons";
import { ProductProps } from "@/sundataImport";
import { useModel } from '@umijs/max';
import { countChineseChars } from "@/services/rwa/product/rwacheckutils";
import { product_modifyone1, product_querylist, rwaCalcConfProductrulesModel } from "@/services/rwa/product_list";

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

    /** 编辑方式，查看、修改、新增按钮时设置，详细信息表单中使用 */
    const [editType, setEditType] = useState<EditType>(prop.editType || 'display');
    /** 是否显示详细信息窗口 */
    const [detailVisible, setDetailVisible] = useState<boolean>(false);
    /** 是否显示产品列表窗口 */
    const [productListVisible, setProductListVisible] = useState<boolean>(false);
    /** 是否显示科目列表窗口 */
    const [subjectListVisible, setSubjectListVisible] = useState<boolean>(false);

    const [productDetailList, setProductDetailList] = useState<boolean>(false);
    // 当前行数据
    const [currentRow, setCurrentRow] = useState<SysListModel>();
    /** 表格引用对象，刷新表格使用   */
    const actionRef = useRef<ActionType>();
    const formRef = useRef<FormInstance<any>>();
    const templateRef = useRef<FormInstance<any>>();

    const productDetailRef =useRef<FormInstance<any>>();

    // 页面数据
    var formDataList = new Array<SysListModel>;
    /**上传文件 */
    const [fileData, setFileData] = useState<File>();
    // 导入窗口显示
    const [importVisible, setImportVisible] = useState<boolean>(false);
    const { fetchDict } = useModel('dict');

    /** 产品列表表单显示 */
    const [mockData, setMockData] = useState<productListModel[]>([]);

    /** 产品列表表单显示 */
    const [subjectMockData, setSubjectMockData] = useState<subjectListModel[]>([]);

    const [mockDetailData, setMockDetailData] = useState<rwaCalcConfProductrulesModel[]>([]);
 
    useEffect(() => {
      }, []);
    
    // 修改查询查询
    const selectData = async (formdata : SysListModel) => {
      const data = await selectDetailData(formdata);
      formRef.current?.setFieldsValue(data);
     }

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

  // 插入或者更新数据
  const handleSave = async(data: SysListModel,) => {
    
    if (editType == 'update' ) {
      if (currentRow?.businessCode) {
        await updateExistData(data,currentRow?.businessCode);
        closeAndRefresh();
      } 
    
    } else if (editType == 'create' ) {
      await fetchDetailData(data);
      closeAndRefresh();
    }
    setDetailVisible(false);
  }



  /**查询产品列表 */
  const selectProductList= async (record: SysListModel) => {
    if (record.businessCode) {
      const data =  await selectProductData(record.businessCode);
      setMockData(data);
    }

  }

  /**查询科目列表 */
  const selectSubjectList = async (record: SysListModel) => {
    if (record.businessCode) {
      const data = await selectSubjectData(record.businessCode);
      setSubjectMockData(data);
    }
    
  }

  // 删除
  const delRows =async(record:any)=>{ 
      baseFun.confirm('请确认是否继续操作？',async() =>{
      await deleteRows(record.businessCode);
      baseFun.info("删除成功");
      closeAndRefresh();
    });
  }

  // 校验
  const roleidCheck = (bussinessCode: string) => isNotExist({
    businessCode:bussinessCode,
  });


  
    // 页面展示元素
    const columns: ProColumns<SysListModel>[] = [
      {
        title: '序号',
        dataIndex: 'index',
        search: false,
        render: (text, record, index) => index + 1,
        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: 'dataDate',
          search: false,
          hideInTable: true,
        },
        {
          title: '业务编号', 
          dataIndex: 'businessCode',
          hideInTable: false,
        },
        {
          title: '业务名称', 
          dataIndex: 'businessName',
          hideInTable: false,
        },
        {
          title: '表内外标识', 
          dataIndex: 'businessAttr',
          search: false,
          hideInTable: false,
        },
        {
          title: '操作',
          dataIndex: 'operate',
          valueType: 'option',
          render: (_, record) => [
            <SDOperate
              key="roleCfg"
              icon={<WomanOutlined />}
              successMessage=""
              onClick={
                ()=>{
                selectData(record);
                setCurrentRow(record);
                setDetailVisible(true);
                setEditType('update')
               } }
            >
              修改
            </SDOperate>,
            <SDOperate
            key="roleCfg"
            icon={<WomanOutlined />}
            successMessage=""   
            onClick={()=>{
              delRows(record) } }
            >
            删除
            </SDOperate>,
            <SDOperate
            key="roleCfg"
            icon={<WomanOutlined />}
            successMessage=""   
            onClick={()=>{
              selectProductList(record);
              setProductListVisible(true);} }
            >
            产品列表
            </SDOperate>,
            <SDOperate
            key="roleCfg"
            icon={<WomanOutlined />}
            successMessage=""   
            onClick={()=>{
              selectSubjectList(record);
              setSubjectListVisible(true);
              } }
            >
            科目列表
            </SDOperate>,
          ],
        },

      ];

    // 页面展示元素
    const productColumns: ProColumns<productListModel>[] = [
      {
        title: '产品编号',
        dataIndex: 'productNo',
        search: false,
        hideInTable: false,
      },
      {
        title: '产品名称',
        dataIndex: 'productName',
        search: false,
        hideInTable: false,
      },
      {
        title: '产品分类',
        dataIndex: 'productType',
        search: false,
        hideInTable: false,
      },
      {
        title: '表内外标识',
        dataIndex: 'onOrOff',
        search: false,
        hideInTable: false,
      },
      {
        title: '来源系统',
        dataIndex: 'productFromSystem',
        search: false,
        hideInTable: false,
      },
      {
        title: '操作',
        dataIndex: 'operate',
        valueType: 'option',
        render: (_, record) => [
          <SDOperate
          key="roleCfg"
          icon={<WomanOutlined />}
          successMessage=""   
          onClick={async ()=>{
            setProductDetailList(true);
            // 产品参数查看实现
            const detailData = await product_modifyone1(record.productNo);
            productDetailRef.current?.setFieldsValue(detailData);
            const detailList = await product_querylist(record.productNo);
            setMockDetailData(detailList);
          } }
          >
          查看
          </SDOperate>,
        ],
      },
    ]

    // 页面展示元素
    const subjectColumns: ProColumns<subjectListModel>[] = [
      {
        title: '产品编号',
        dataIndex: 'productNo',
        search: false,
        hideInTable: false,
      },
      {
        title: '产品名称',
        dataIndex: 'productName',
        search: false,
        hideInTable: false,
      },
      {
        title: '科目编号',
        dataIndex: 'ruleCode',
        search: false,
        hideInTable: false,
      },
      {
        title: '科目名称',
        dataIndex: 'ruleCode',
        search: false,
        hideInTable: false,
        valueType: "treeSelect",
          request: () => fetchDict('org'),
          fieldProps: {
          treeDefaultExpandAll: true,
          treeCheckable:true,
          },
      },
      {
        title: '数据类型',
        dataIndex: 'dataType',
        search: false,
        hideInTable: false,
      },
    ]

    const columns1: ProColumns<rwaCalcConfProductrulesModel>[] = [
      { title : '计算实例号',
      dataIndex : 'calcindex',
      search:false,
      hideInTable:true,
      width : 150
      },
      
      { title : '起始数据日期',
      dataIndex : 'sdate',
      search:false,
      hideInTable:true,
      width : 150
      },
      
      { title : '截止数据日期',
      dataIndex : 'edate',
      search:false,
      hideInTable:true,
      width : 150
      },
      
      { title : '年月',
      dataIndex : 'term',
      search:false,
      hideInTable:true,
      width : 150
      },
      
      { title : '数据日期',
      dataIndex : 'dataDate',
      search:false,
      hideInTable:true,
      width : 150
      },
      
      { title : '产品编号',
      dataIndex : 'productNo',
      search:false,
      hideInTable:true,
      width : 150
      },
      
      { title : '规则编号',
      dataIndex : 'ruleCode',
      width : 150
      },
      
      { title : '规则名称',
      dataIndex : 'ruleName',
      width : 150
      },

      { title : '数据类型',
      dataIndex : 'dataType',
      width : 150
      },
      
      { title : '对应科目号',
      dataIndex : 'ruleSubject',
      width : 150
      },
      
      { title : '输入数据源',
      dataIndex : 'ruleIn',
      width : 150
      },
      
      { title : '输出数据源',
      dataIndex : 'ruleOut',
      width : 150
      },
      
      { title : '科目取数规则',
      dataIndex : 'ruleGetdata',
      width : 150
      },
      { title : '规则序号',
      dataIndex : 'ruleIndex',
      width : 150
      },]
    
    return (
        <SDPage>
        <SDTable
         title="查询表格"
         rowKey="customerName"
         request={async (formdata:SysListModel) =>{
           const formDatas = await getDataList(formdata);
           // 解构数组（导出用）
           formDataList=[...formDatas];
           return {data: formDatas}
         }  }
         columns={columns}
         operations={['create']}
         actionRef={actionRef}
         formRef={formRef}
         setDetailVisible={() => {setDetailVisible(true)}}
         setEditType={setEditType}
         setCurrentRow={setCurrentRow}
         />

        {detailVisible && (
        <SDModalForm          
          title={'详细信息'}
          editType={editType}
          params={currentRow}
          visible={detailVisible}
          onVisibleChange={() => {setDetailVisible(false)}}
          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="businessCode" readonlyCond="update" bgValidater={roleidCheck} rules={[{max:20,message:'不可超过20个字符'},]}  label="业务编号"/>
            <SDFormText name="businessName"  label="业务名称" rules={[{validator:(rules,value,callback)=>{
            let chineseCount = countChineseChars(value);
            if (chineseCount > 50) {
                callback('最多50个汉字');
            } else if (chineseCount<=0) {
                callback('请输入汉字');
            } else{
              callback();
            }
         }}]}/>
            <SDFormDict name="businessAttr" dictKey="ONOROFF" label="表内外标识"/>
        </SDModalForm>
        
      )}
      

      {productListVisible && 
      <SDModalForm 
      title={'产品列表'} 
      visible={productListVisible} 
      editType={editType} 
      onVisibleChange={() => { setProductListVisible(false);}
    }>
      <SDLayout>
      <ProTable
        rowKey="productNo"
        search={false} 
        dataSource={mockData}
        columns={productColumns}
        //singleSelect={false}
       actionRef={actionRef}
       formRef={formRef}
        />
      </SDLayout>
      </SDModalForm>
      }


     {subjectListVisible && 
      <SDModalForm 
      title={'科目列表'} 
      visible={subjectListVisible} 
      editType={editType} 
      onVisibleChange={() => { setSubjectListVisible(false);}
      }>
      <SDLayout>
      <ProTable
        rowKey="productNo"
        search={false} 
        dataSource={subjectMockData}
        columns={subjectColumns}
       actionRef={actionRef}
       formRef={formRef}
        />
     </SDLayout>
      </SDModalForm>
      }


      {productDetailList &&
      <SDModalForm 
      title={'产品列表'} 
      visible={productDetailList} 
      editType={editType}
      formRef={productDetailRef}
      onVisibleChange={() => { setProductDetailList(false);}
    }>
     <SDFormText name="productNo"   label="产品代码"  />
    <SDFormText name="productName"   label="产品名称"  />
    <SDFormText name="productType"   label="产品大类"  />
    <SDFormText name="productIndex"   label="产品序号"  />
    <SDFormText name="productStageId"   label="所属阶段"  />
    <SDFormText name="productFromSystem"   label="来源系统"  />
    <SDFormText name="defaultOut"   label="默认输出数据源"  />
    <SDFormText name="productBussinessCode"   label="所属业务"  />
    <SDFormText name="defaultGetdatarule"   label="默认取数逻辑"  />

      <SDAreaTtile title='科目取数规则列表' />
      <SDLayout>
        <ProTable
            rowKey="ruleCode"
            search={false} 
            formRef={productDetailRef}
            dataSource={mockDetailData}
            columns={columns1}
        />
      </SDLayout>
      </SDModalForm>

      }
    </SDPage>
    );
}
export default bussiness;

