import {defineStore} from 'pinia';
import {fetchTemplatesPage} from "/@/api/config/templateManage";

/**
 * 调用模板 并返回 模板id
 * */
export const templateStore = defineStore('templateStore',{
    state: () => ({
        temp_id:'',
        query:{
            current:1,
            size:10,
            templateName:''
        },
        tempData:[] as any[],
        showTemp:false,
        total:0,
        loading:false,
        type:-1,
    }),
    getters: {
        getShowTemp: (state):boolean => {
            return state.showTemp
        },
    },
    actions:{
        /**
         * 切换模板显示
         * */
        changeTempShow(flag:boolean,type?:number){
            this.showTemp = flag;
            if(this.showTemp){
                this.getTempData(type).then(()=>{})
            }else {
                this.query.templateName = '';
                this.query.current = 1;
                this.query.size = 10;
            }
        },
        /**
         * 获取模板数据
         * */
        async getTempData(type:number|undefined){
            this.type = type as number;
           try {
               this.loading = true
               const res = await fetchTemplatesPage(this.query)
               if (type){
                   this.tempData = res.data.records.filter((item:any)=>{
                       return item.templateType === type
                   })
               }else {
                   this.tempData = res.data.records
               }
               this.total = res.data.total
           }catch (e) {
               return e
           }finally {
               this.loading = false
           }
        },
        /**
         * 切换分页
         * */
        async changePage(page:number){
            this.query.current = page;
            await this.getTempData(this.type);
        },
        /**
         * 切换 每页数量
         * */
        async changePageSize(size:number){
            this.query.size = size;
            await this.getTempData(this.type);
        },
        /**
         * 根据模板名称查询
         * */
        async queryByName(name:string){
            this.query.templateName = name;
            await this.getTempData(this.type);
        },
        /**
         *获取模板id
         * */
        getTempId(row:any){
            this.temp_id = row.id
        },
    },
})