<script setup lang="tsx">
import { reactive, ref, unref } from 'vue'
import {
  getRepIndexSearchListApi} from '@/api/dataset/RepIndexSet'
import { TableData } from '@/api/reporting/RepDataProblem/RepDataProblem/types'
import { useTable } from '@/hooks/web/useTable'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import { ElButton, ElLink, ElLoading, ElPopconfirm, ElMessage,ElDropdown,ElDropdownMenu,ElDropdownItem } from 'element-plus'
import { Search } from '@/components/Search'
import { FormSchema } from '@/components/Form'
import { ContentWrap } from '@/components/ContentWrap'
import DrillingOrAnalysis from './components/DrillingOrAnalysis.vue'
import { Dialog } from '@/components/Dialog'
import { getWidth } from '@/utils';
import { useValidator } from '@/hooks/web/useValidator'
import { getLoginOrganCodeByUserInfo } from '@/utils/auth'
import { getOrganTree } from '@/api/common'
import { getIndexType } from '@/api/dataset/RepIndexSet';
import { transfDictList } from '@/utils';


import {useRoute} from "vue-router"
import { getDateByPrevMonth } from '@/utils/dateUtil'
const route = useRoute();
const date = getDateByPrevMonth();
const pageQuery = ref(route || null);
    const indexsetCode = pageQuery.value?.query?.indexsetCode;
    const reportDate = pageQuery.value?.query?.reportDate;
    const organId = pageQuery.value?.query?.organId;
    const frequency = pageQuery.value?.query?.frequency;
    const code = pageQuery.value?.query?.code;

let frequency_param_LIST = ref([]);

//获取字典项
const getDictInfoList = async ()=>{
    const res = await getIndexType({ paramName: 'frequency_param', systemCode: 'ordb' });
    frequency_param_LIST.value = transfDictList(res.body.result);
}
getDictInfoList();

defineOptions({
  name: 'IndexSearchServiceMs',
});
const { t } = useI18n()
const { required } = useValidator();

// 获取当前用户机构号
const loginOrganCode = getLoginOrganCodeByUserInfo();
const ids = ref<string[]>([])

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await getRepIndexSearchListApi({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      indexsetCode:indexsetCode,
      ...unref(searchParams)
    })
    return {
      list: res.body.list,
      total: res.body.total
    }
  },
  fetchDelApi: async () => {
    const res = await delRepDataProblemListApi(unref(ids));
    return !!res;
  },
})

const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList, refresh } = tableMethods

const tableColumns = reactive<TableColumn[]>([
  {
    field: 'selection',
    type: 'selection',
    fixed: true
  },
    {
      field: 'organName',
      label: '机构名称'
    },
    {
      field: 'paramDate',
      label: '数据日期'
    },
  {
    field: 'indexSetCode',
    label: '指标集编码',
    hidden: true
  },
  {
      field: 'indexSetName',
      label: '指标集名称',
      hidden: true
  },
  {
      field: 'indexItemCode',
      label: '指标代码'
  },
  {
      field: 'itemName',
      label: '指标名称'
  },
  {
    field: 'indexTargetCode',
    label: '指标属性'
  },
  {
    field: 'targetName',
    label: '指标属性名称'
  },
  {
    field: 'frequency',
    label: '频度',
    slots:{
             default:(data)=>{
                return <span>{data.row.frequency?frequency_param_LIST.value[data.row.frequency]?.label:''}</span>
             }
        }
  },
  {
    field: 'indexValue',
    label: '本期值',
    slots:{
      default:(data:any)=>{
        return <ElDropdown class="{prefixCls} custom-hover" style="vertical-align: middle;padding:0;" trigger="contextmenu" placement="right">
                  {{
                    default:()=>{
                      return <div>
                        <span class="canOperate">{data.row.indexValue}</span>
                      </div>
                    },
                    dropdown:()=>{
                      return <ElDropdownMenu>
                        <ElDropdownItem onClick={()=>action(data.row,'DrillingByOrgan','按机构钻取','indexValue')}>
                          <div>按机构钻取</div>
                        </ElDropdownItem>
                        <ElDropdownItem onClick={()=>action(data.row,'TrendAnalysis','趋势分析','indexValue')}>
                          <div>趋势分析</div>
                        </ElDropdownItem>
                      </ElDropdownMenu>
                    }
                  }}
            </ElDropdown>
      }
    }
  },
  {
    field: 'prevPeriodValue',
    label: '上期值',
    slots:{
      default:(data:any)=>{
        return <ElDropdown class="{prefixCls} custom-hover" style="vertical-align: middle;padding:0;" trigger="contextmenu" placement="right">
                  {{
                    default:()=>{
                      return <div>
                        <span>{data.row.prevPeriodValue}</span>
                      </div>
                    },
                    dropdown:()=>{
                      return <ElDropdownMenu>
                        <ElDropdownItem onClick={()=>action(data.row,'DrillingByOrgan','按机构钻取','prevPeriodValue')}>
                          <div>按机构钻取</div>
                        </ElDropdownItem>
                        <ElDropdownItem onClick={()=>action(data.row,'TrendAnalysis','趋势分析','prevPeriodValue')}>
                          <div>趋势分析</div>
                        </ElDropdownItem>
                      </ElDropdownMenu>
                    }
                  }}
            </ElDropdown>
      }
    }
  }
].map(item => ({ minWidth: item.label ? getWidth(item.label) : 120, ...item }) as TableColumn))

const searchSchema = reactive<FormSchema[]>([
  {
    field: 'organId',
    label: '机构',
    colProps: { span: 100 },
    componentProps: {
      checkStrictly: true,
      nodeKey: 'key',
      props: { children: 'childrens', label: 'value' },
      filterable: true,
      multiple: false,
      collapseTags: true,
      showCheckbox: true,
      // style: { minWidth: '200px' },
      //style: 'width: 100%',
      checkOnClickNode: true,
    },
    component: 'TreeSelect',
    optionApi: async () => {
      const res = await getOrganTree({
        treeid: '1',
        systemCode: 'portal',
        loginOrganCode,
      });
      return res.body.result;
    },
    value: loginOrganCode,
    formItemProps: {
      rules: [required()],
    },
  },
  {
    field: 'reportDate',
    label: '日期',
    componentProps: {
      type: 'date',
      valueFormat: 'YYYYMMDD',
    },
    component: 'DatePicker',
    formItemProps: {
      rules: [required()],
    },
    value:date
  },
  {
    field: 'itemAndTarget',
    label: '指标代码',
    componentProps: {},
    component: 'Input',
    formItemProps: {
      rules: [required()],
    },
    value:code
  }
])

const searchParams = ref({})
const setSearchParams = (data: any) => {
  searchParams.value = data
  getList()
}
setSearchParams({indexsetCode:indexsetCode,reportDate:reportDate,organId:organId,frequency:frequency,code:code});
const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref()
const actionType = ref('')

const DrillingType = ref('');//钻取类型
/**单行查询——按机构钻取
  row:当前行的数据信息
  type:当前的操作类型
  dialogTitle:弹框的标题
  column:当前操作的列是本期值还是哪一期的值
**/
const action = async (row: TableData, type: string,title: string,column: string) => {
  dialogTitle.value = title;//弹窗标题
  actionType.value = column;//当前的操作类型
  currentRow.value = row;//当前点击行的信息
  DrillingType.value = type;//钻取类型
  dialogVisible.value = true;//打开弹框
}

const disabled = ref(true);

const onSelectionChange = (selection: TableData[]) => {
  disabled.value = selection.length === 0
}
const onContextMenu = (row: any, column: any, cell: HTMLTableCellElement, event: Event) => {

}


</script>

<template>
  <ContentWrap>
    <Search :schema="searchSchema" @reset="setSearchParams" @search="setSearchParams" />

    <Table
      :columns="tableColumns"
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      default-expand-all
      node-key="pId"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total
      }"
      @selection-change="onSelectionChange"
      @register="tableRegister"
      @refresh="refresh"
      @cell-contextmenu="onContextMenu"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle" style="min-width:800px;">
    <DrillingOrAnalysis
      ref="DrillingOrAnalysisRef"
      :current-row="currentRow"
      :action-type="actionType"
      :drillingType="DrillingType"
    />
  </Dialog>
</template>