import {BasicColumn} from '/@/components/Table';
import {FormSchema} from '/@/components/Table';
import { rules} from '/@/utils/helper/validator';
import { render } from '/@/utils/common/renderUtils';
import {defHttp} from '/@/utils/http/axios';
//列表数据
export const columns: BasicColumn[] = [
  {
    title: '类型',
    align:"center",
    dataIndex: 'tp',
    resizable:true,
    sorter:true,
    width:80,
    customRender: ({ text }) => {
      return render.renderDict(text, 'metric_sta_report_tp');
    },
   },
   {
    title: '主标题',
    align:"left",
    dataIndex: 'title',
    resizable:true,
    sorter:true,
    width:180
   },
   {
    title: '副标题',
    align:"left",
    dataIndex: 'subtitle',
    resizable:true,
    sorter:true,
    width:140
   },
   {
    title: '报告部门',
    align:"left",
    dataIndex: 'reportDepart_dictText',
    resizable:true,
    sorter:true,
    width:130
   },
  //  {
  //   title: '报告日期',
  //   align:"center",
  //   dataIndex: 'reportDate',
  //   resizable:true,
  //   sorter:true,
  //   width:100,
  //   customRender:({text}) =>{
  //     return !text?"":(text.length>10?text.substr(0,10):text)
  //   },
  //  },
   {
    title: '开始日期',
    align:"center",
    dataIndex: 'stDate',
    resizable:true,
    sorter:true,
    width:100,
    customRender:({text}) =>{
      return !text?"":(text.length>10?text.substr(0,10):text)
    },
   },
   {
    title: '结束日期',
    align:"center",
    dataIndex: 'endDate',
    resizable:true,
    sorter:true,
    width:100,
    customRender:({text}) =>{
      return !text?"":(text.length>10?text.substr(0,10):text)
    },
   },
   {
    title: '统计方法',
    align:"center",
    dataIndex: 'statMethod',
    resizable:true,
    sorter:true,
    width:90,
    customRender: ({ text }) => {
      return render.renderDict(text, 'metric_sta_method');
    },
    
   },

   {
    title: '风险指标统计',
    align:"center",
    children:[
    {
      title: '总数',
      align:"center",
      dataIndex: 'statTargetNum',
      resizable:true,
      sorter:true,
      width:60
    },
    {
      title: '低风险',
      align:"center",
      dataIndex: 'riskLowNum',
      resizable:true,
      sorter:true,
      width:60
    },
    {
      title: '中风险',
      align:"center",
      dataIndex: 'riskMediumNum',
      resizable:true,
      sorter:true,
      width:60
    },
    {
      title: '高风险',
      align:"center",
      dataIndex: 'riskHighNum',
      resizable:true,
      sorter:true,
      width:60
    },
    {
      title: '其他',
      align:"center",
      dataIndex: 'riskOtherNum',
      resizable:true,
      sorter:true,
      width:60
    },
  ]}
];
//查询数据
export const searchFormSchema: FormSchema[] = [
  {
    label: '报告类型',
    field: 'tp',
    component: 'JDictSelectTag',
    componentProps: {
      dictCode: 'metric_sta_report_tp',
      type: 'radio',
      stringToNumber: true,
    }
  },
  {
    label: '报告主标题',
    field: 'title',
    component: 'Input',
  },
];
//表单数据
export const formSchema: FormSchema[] = [

  {
    label: '报告类型',
    field: 'tp',
    component: 'JDictSelectTag',
    // defaultValue:2,
    dynamicRules: ({model,schema}) => {
      return [
        { required: true},
      ];
    },
    componentProps: ({ formActionType, formModel }) => {
      return {
        dictCode: 'metric_sta_report_tp',
        type: 'radio',
        stringToNumber: true,
        sync: true,
        onChange: async (tp) => {
          const { updateSchema } = formActionType;
          const objTmp={2:"week",3:"month",4:"quarter",6:"year"}
          const statSetMap =  await getMetricStatSet();
        
          updateSchema([
            {
              field: 'reportDate',
              componentProps: { 
                picker:objTmp[tp],
                valueFormat: 'YYYY-MM-DD',
                onChange: (val) => {
                  let date = new Date(val);
                  let year = date.getFullYear();
                  let month = date.getMonth()+1;
                  let stDate = "";
                  let endDate="";
                  if(formModel.tp==2) {
                    let day = date.getDay();
                    let diff = date.getDate() - day + (day == 0 ? -6:1); 
                    let monday = new Date(date.setDate(diff));
                    let sunday = new Date(monday);
                    sunday.setDate(monday.getDate() + 6); 
                    stDate = monday.toISOString().slice(0, 10)
                    endDate = sunday.toISOString().slice(0, 10)
                  } else  if(formModel.tp==3) {
                    let firstDate = year + "-" + (month<10?'0'+month:month) +"-01";
                    let lastDate = new Date(year, month, 0).getDate();
                    stDate = firstDate;
                    endDate =  year + "-" + (month<10?'0'+month:month) + "-" + lastDate

                  } else  if(formModel.tp==4) {
                    let firstDate = date;
                    let quarter = Math.floor((firstDate.getMonth() + 3) / 3); 
                    let lastMonth = quarter * 3; 
                    let lastDate = new Date(year, lastMonth, 0).getDate(); 
                    stDate = firstDate.toISOString().slice(0, 10)
                    endDate = year + "-" + (lastMonth<10?'0'+lastMonth:lastMonth) + "-" + lastDate
                  } else  if(formModel.tp==6) {
                    stDate = year + "-01-01";
                    endDate = year + "-12-31"
                  }
            
                  formModel.stDate=stDate
                  formModel.endDate= endDate
                }
               },
            },
          ]);

          formModel.reportDate=''
          formModel.stDate= ""
          formModel.endDate= ""
          if(statSetMap) {
            const tmpStaSet = statSetMap[tp];
            if(tmpStaSet) {
              formModel.title=tmpStaSet.heading
              formModel.subtitle= tmpStaSet.subtitle
              formModel.reportDepart = tmpStaSet.departId
              formModel.statMethod = tmpStaSet.statMethod
            }
          
          }
         
        },
      };
    },
    
  },
  {
    label: '主标题',
    field: 'title',
    component: 'Input',
    dynamicRules: ({model,schema}) => {
      return [
        { required: true, message: '请输入主标题!'},
        { min: 0, max: 32, message: '长度不能超过 32 个字符', trigger: 'blur' },
      ];
    },
  },
  {
    label: '副标题',
    field: 'subtitle',
    component: 'Input',
    dynamicRules: ({model,schema}) => {
      return [
        { required: false, message: '请输入主标题!'},
        { min: 0, max: 32, message: '长度不能超过 32 个字符', trigger: 'blur' },
      ];
    },
  },
  {
    label: '监测时间',
    field: 'reportDate',
    component: 'DatePicker',
    dynamicRules: ({model,schema}) => {
      return [
        { required: true},
      ];
    },
    componentProps: ({ formActionType, formModel }) => {
      return {
        valueFormat: 'YYYY',
        format: "YYYY",
      };
    },
  },
  {
    label: '开始日期',
    field: 'stDate',
    component: 'DatePicker',
    dynamicDisabled:true,
    dynamicRules: ({model,schema}) => {
      return [
        { required: true},
      ];
    },
    componentProps: ({ formActionType, formModel }) => {
      return {
        valueFormat: 'YYYY-MM-DD',
        format: "YYYY-MM-DD",
      };
    },
  },
  {
    label: '结束日期',
    field: 'endDate',
    component: 'DatePicker',
    dynamicDisabled:true,
    dynamicRules: ({model,schema}) => {
      return [
        { required: true},
      ];
    },
    componentProps: {
      valueFormat: 'YYYY-MM-DD',
      format: "YYYY-MM-DD",
      picker:"week"
    },
  },
  {
    label: '报告部门',
    field: 'reportDepart',
    component: 'JSelectDept',
    dynamicRules: ({model,schema}) => {
      return [
        { required: true},
      ];
    },
  },
  {
    label: '统计指标数',
    field: 'statTargetNum',
    component: 'InputNumber',
  },
  {
    label: '低风险指标数',
    field: 'riskLowNum',
    component: 'InputNumber',
  },
  {
    label: '中风险指标数',
    field: 'riskMediumNum',
    component: 'InputNumber',
  },
  {
    label: '高风险指标数',
    field: 'riskHighNum',
    component: 'InputNumber',
  },
  {
    label: '统计方法',
    field: 'statMethod',
    component: 'JDictSelectTag',
    defaultValue:1,
    componentProps: {
      dictCode: 'metric_sta_method',
      type: 'radio',
      stringToNumber: true,
    }
  },
	// TODO 主键隐藏字段，目前写死为ID
	{
	  label: '',
	  field: 'id',
	  component: 'Input',
	  show: false
	},
];


async function getMetricStatSet() {
  try {
    const ret = await defHttp.get({ url: '/metric/metricStatSet/list' });
    const tpMap = {};
    for (const data of ret.records) {
      tpMap[data.tp] = data;
    }
    return tpMap;
  } catch (error) {
    console.error('Error fetching metric stat set:', error);
    return {}; 
  }
}

/**
* 流程表单调用这个方法获取formSchema
* @param param
*/
export function getBpmFormSchema(_formData): FormSchema[]{
  // 默认和原始表单保持一致 如果流程中配置了权限数据，这里需要单独处理formSchema
  return formSchema;
}