// nuxt 3 - plugins/my-plugin.ts
import { useStore } from '~/stores/index'
import axios from 'axios'

export default defineNuxtPlugin(() => {
  const module = 'system'
  const mode = 'dev'
  const paths = [
    { name: "dev", url: "https://api.utopia.com.vn/" },
    { name: "local", url: "http://localhost:8000/" },
    { name: "prod", url: "https://api.utopia.com.vn/" },
  ];
  const path = paths.find(v=>v.name===mode).url
  const apis = [
    {name: 'bizrights', url: 'data/Biz_Rights/', url_detail: 'data-detail/Biz_Rights/', params: {sort: '-id'}},
    { name: "bizsetting", url: "data/Biz_Setting/", url_detail: "data-detail/Biz_Setting/", params: {}},
    {name: 'backup', url: 'data/Backup/', url_detail: 'data-detail/Backup/', params: {sort: '-id', values: 'id,code,name,status,status__name,start_time,end_time,create_time,file'}},
    {name: 'apps', url: 'data/Apps/', url_detail: 'data-detail/Apps/', params: {sort: 'id'}},
    {name: 'relation', commit: 'relation', url: 'data/Relation/', url_detail: 'data-detail/Relation/', params: {}},
    {name: 'systemsetting', commit: 'common', url: 'data/System_Setting/', url_detail: 'data-detail/System_Setting/', params: {sort: 'index'}},
    {name: 'approvestatus', url: 'data/Approve_Status/', url_detail: 'data-detail/Approve_Status/', params: {}},
    {name: 'staffstatus', url: 'data/Staff_Status/', url_detail: 'data-detail/Staff_Status/', params: {}},
    {name: 'userapps', url: 'data/User_Apps/', url_detail: 'data-detail/User_Apps/', params: {}},
    {name: 'dealer', url: 'data/Dealer/', url_detail: 'data-detail/Dealer/', params: {values: 'id,code,name,user,user__username,user__fullname,email,create_time'}},
    {name: 'datadeletion', url: 'data-deletion/', params:  {}},
    {name: 'emailsetup', url: 'data/Email_Setup/', url_detail: 'data-detail/Email_Setup/', params: {sort: '-id'}},
    {name: 'emailsent', url: 'data/Email_Sent/', url_detail: 'data-detail/Email_Sent/', params: {values: 'id,subject,sender,sender__email,receiver,content,status__code,status,status__name,create_time', sort: '-id'}},
    {name: 'sendemail', url: 'send-email/', params: {}},
    {name: 'message', url: 'data/Message/', params: {sort: '-id'}},
    { name: "exportcsv", url: "exportcsv/", params: {} },

    {name: 'staff', url: 'data/Staff/', url_detail: 'data-detail/Staff/', params: {
      values: 'id,zalo,facebook,status,status__name,status__en,country__en,user__username,country,country__code,branch__code,creator,updater,updater__fullname,creator__fullname,issued_date,code,email,fullname,dob,sex,legal_code,sex__name,phone,legal_type,legal_type__name,legal_code,address,note,updater,updater__fullname,create_time,update_time,issued_place', 
      distinct_values: {label: {type: 'Concat', field: ['code', 'fullname', 'phone']}, order: {type: 'RowNumber'}
    }, filter: {deleted: 0}, sort: '-id', summary: 'annotate'}},
    {name: 'applyresult', url: 'data/Apply_Result/', url_detail: 'data-detail/Apply_Result/', params:  {sort: 'id'}},
    {name: 'langchoice', url: 'data/Lang_Choice/', url_detail: 'data-detail/Lang_Choice/', params:  {sort: 'id'}},
    {name: 'displaystatus', url: 'data/Display_Status/', url_detail: 'data-detail/Display_Status/', params:  {sort: 'id'}},
    {name: 'datastory', url: 'data/Data_Story/', url_detail: 'data-detail/Data_Story/', params:  {sort: '-id', values: 'id,title,subtitle,image,header,content,link,canonical,category,status,language,language__code,language__name,valid_from,valid_to,user,create_time,update_time'}},
    {name: 'news', url: 'data/News/', url_detail: 'data-detail/News/', params:  {sort: '-id', values: 'id,title,subtitle,image,header,content,link,canonical,category,status,language,language__code,language__name,valid_from,valid_to,user,create_time,update_time'}},
    {name: 'promotion', url: 'data/Promotion/', url_detail: 'data-detail/Promotion/', params:  {sort: '-id', values: 'id,title,subtitle,image,header,content,link,canonical,category,status,language,language__code,language__name,valid_from,valid_to,user,create_time,update_time'}},
    {name: 'file', url: 'data/File/', url_detail: 'data-detail/File/', params:  {sort: '-id'}},
    {name: 'token', url: 'data/Token/', url_detail: 'data-detail/Token/', params: {values: 'id,token,browser,browser_version,ip,os,platform,expiry,create_time,update_time,user,user__fullname,user__username', sort: '-id'}},
    {name: 'authtoken', url: 'auth-token/', params: {}},
    {name: 'notification', commit: 'updateNotification', url: 'data/Notify/', url_detail: 'data-detail/Notify/', params: {values:'id,title,content,image,link,task_log,user,user__username,user__fullname,event,seen,create_time,event__code,event__name,update_time'}},
    {name: 'settingapp', url: 'data/Setting_App/', url_detail: 'data-detail/Setting_App/', params: {sort: 'index'}}, 
    {name: 'upload', url: 'upload/', params: {}},
    {name: 'sendemail', url: 'send-email/', path: 'etl', params: {}},
    {name: 'sendemailnow', url: 'send-email-now/', path: 'etl', params: {}},
    {name: 'usersession', url: 'data/User_Session/', url_detail: 'data-detail/User_Session/', params: {values: 'id,token,balance,duration,start_time,end_time,session,create_time',
       distinct_values: {
      files: {type: 'ArrayAgg', field: ['usersession__file__file']}
      }, sort: '-id', summary: 'annotate'}
    },
    {name: 'stafffile', url: 'data/Staff_File/', url_detail: 'data-detail/Staff_File/', 
    params: {values: 'id,ref,file,file__name,file__file'}},
    {name: 'usersetting', url: 'data/User_Setting/', url_detail: 'data-detail/User_Setting/', params: {}},
    {name: 'settingfields', url: 'data/User_Setting/', url_detail: 'data-detail/User_Setting/', params: {}},
    {name: 'settingclass', commit: 'settingclass', url: 'data/Setting_Class/', url_detail: 'data-detail/Setting_Class/', params: {}},
    {name: 'user', url: 'data/User/', url_detail: 'data-detail/User/', params: {sort: '-id', values: 'id,email,is_admin,type__en,type__name,auth_method__code,blocked,auth_status__code,username,register_method__code,fullname,type,type__code,type__name,create_time,create_time__date,auth_method,auth_status,register_method,create_time,update_time',
      distinct_values: {label: {type: 'Concat', field: ['username', 'fullname']},
      "apps": {"type": "ArrayAgg", "field": ["userapps__id", "userapps", "userapps__apps", "userapps__apps__code"]}}, 
      summary: 'annotate'
    }},
    {name: 'gethash', url: 'get-hash/', params: {}},
    {name: 'login', url: 'login/', params: {values: 'id,username,password,avatar,fullname,display_name,type,type__code,type__name,blocked,block_reason,block_reason__code,block_reason__name,blocked_by,last_login,auth_method,auth_method__code,auth_method__name,auth_status,auth_status__code,auth_status__name,register_method,register_method__code,register_method__name,create_time,update_time'}},
    {name: 'settingtype', commit: 'settingtype', url: 'data/Setting_Type/', url_detail: 'data-detail/Setting_Type/', params: {}},
    {name: 'colorchoice', commit: 'colorchoice', url: 'data/Color_Choice/', url_detail: 'data-detail/Color_Choice/', params: {sort: 'id'}},
    {name: 'filterchoice', commit: 'filterchoice', url: 'data/Filter_Choice/', url_detail: 'data-detail/Filter_Choice/', params: {sort: 'id'}},
    {name: 'datatype', commit: 'datatype', url: 'data/Data_Type/', url_detail: 'data-detail/Data_Type/', params: {sort: 'id'}},
    {name: 'textalign', commit: 'textalign', url: 'data/Text_Align/', url_detail: 'data-detail/Text_Align/', params: {sort: 'id'}},
    {name: 'placement', commit: 'placement', url: 'data/Placement/', url_detail: 'data-detail/Placement/', params: {sort: 'id'}},
    {name: 'colorscheme', commit: 'colorscheme', url: 'data/Color_Scheme/', url_detail: 'data-detail/Color_Scheme/', params: {sort: 'id'}},
    {name: 'textcolor', commit: 'textcolor', url: 'data/Text_Color/', url_detail: 'data-detail/Text_Color/', params: {sort: 'id'}},
    {name: 'filtertype', commit: 'filtertype', url: 'data/Filter_Type/', url_detail: 'data-detail/Filter_Type/', params: {sort: 'id'}},
    {name: 'sorttype', commit: 'sorttype', url: 'data/Sort_Type/', url_detail: 'data-detail/Sort_Type/', params: {sort: 'id'}},
    {name: 'tablesetting', commit: 'tablesetting', url: 'data/Table_Setting/', url_detail: 'data-detail/Table_Setting/', params: {sort: 'id', values: 'id,code,name,detail'}},
    {name: 'settingchoice', commit: 'settingchoice', url: 'data/Setting_Choice/', url_detail: 'data-detail/Setting_Choice/', params: {sort: 'id'}},
    {name: 'menuchoice', commit: 'menuchoice', url: 'data/Menu_Choice/', url_detail: 'data-detail/Menu_Choice/', params: {}},
    {name: 'moneyunit', commit: 'moneyunit', url: 'data/Money_Unit/', url_detail: 'data-detail/Money_Unit/', params: {}},
    {name: 'legaltype', commit: 'legaltype', url: 'data/Legal_Type/', url_detail: 'data-detail/Legal_Type/', params: {page: -1}},
    {name: 'sex', commit: 'sex', url: 'data/Sex/', url_detail: 'data-detail/Sex/', params:  {}},
    {name: 'usertype', commit: 'UserType', url: 'data/User_Type/', url_detail: 'data-detail/User_Type/', params:  {}},
    {name: 'province', commit: 'province', url: 'data/Province/', url_detail: 'data-detail/Province/', params: {}},
    {name: 'customerfile', url: 'data/Customer_File/', url_detail: 'data-detail/Customer_File/', 
    params: {values: 'id,ref,file,file__name,file__file'}},
    {name: 'collaboratorfile', url: 'data/Collaborator_File/', url_detail: 'data-detail/Collaborator_File/', 
    params: {values: 'id,ref,file,file__name,file__file'}},
    {name: 'customer', url: 'data/Customer/', url_detail: 'data-detail/Customer/', params: {
      values: 'id,branch__code,creator,updater,updater__fullname,creator__fullname,issued_date,code,email,fullname,dob,sex,legal_code,sex__name,phone,legal_type,legal_type__name,legal_code,address,note,updater,updater__fullname,create_time,update_time,issued_place', 
      distinct_values: {label: {type: 'Concat', field: ['code', 'fullname', 'phone']}, order: {type: 'RowNumber'}, 
      image_count: {type: 'Count', field: 'custfile__id', subquery: {model: 'Customer_File', column: 'ref'}},
      count_note: {type: 'Count', field: 'custnote__id', subquery: {model: 'Customer_Note', column: 'ref'}}
    },
      filter: {deleted: 0}, sort: '-id', summary: 'annotate'}},
    {name: 'service', commit: 'service',  url: 'data/Service/', url_detail: 'data-detail/Service/', params: {}},
    {name: 'useraction', url: 'data/User_Action/', url_detail: 'data-detail/User_Action/', params: {
      values: 'id,action,action__code,action__name,action__message,action__image,action__file,action__link,user,message,image,file,link,create_time'
    }},
    {name: 'filtersetting', url: 'data/Filter_Setting/', url_detail: 'data-detail/Filter_Setting/', params: {}},
    {name: 'getmodel', url: 'get-model/', params: {}},
    {name: 'paymenttype', url: 'data/Payment_Type/', url_detail: 'data-detail/Payment_Type/', params: {}},
    {"name":"payment","url":"data/Payment/","url_detail":"data-detail/Payment/","params":{values: 'id,service,service__code,service__name,session,session__session,type,type__code,type__name,amount,code,content,detail'}},
    {name: 'datastorycategory', url: 'data/Datastory_Category/', url_detail: 'data-detail/Datastory_Category/', 
    params: {sort: 'id', values: 'id,story,category,category__code,category__name,title,image,url,create_time,update_time'}},
    {name: 'jobapply', url: 'data/Job_Apply/', url_detail: 'data-detail/Job_Apply/', params: {sort: '-id', values: 'id,staff,staff__code,code,fullname,phone,email,address,link,create_time,job,job__title,file,file__file,result,result__code,result__name'}},
    {name: 'collaborator', url: 'data/Collaborator/', url_detail: 'data-detail/Collaborator/', params: {values: 'id,zalo,facebook,bank,bank__name,bank_holder,bank_account,user,user__username,legal_type,status,status__code,status__name,code,fullname,phone,email,address,sex,sex__name,create_time,dob,legal_type__name,legal_code,issue_date,issue_place'}},
    {name: 'collateralcategory' , url: 'data/Collateral_Category/', url_detail: 'data-detail/Collateral_Category/', params:  {sort: 'index'}},
    {name: 'paymenttype', url: 'data/Payment_Type/', url_detail: 'data-detail/Payment_Type/', params: {}},
    {name: 'country', commit: 'country', url: 'data/Country/', url_detail: 'data-detail/Country/', params: {}},
    {name: 'people' , url: 'data/People/', url_detail: 'data-detail/People/', params:  {sort: '-id', values: 'id,email,creator,avatar,code,fullname,dob,sex,legal_code,sex__name,phone,issued_date,legal_type,legal_type__name,legal_code,address,note,updater,updater__fullname,create_time,update_time,issued_place'}},
    {name: 'branchtype' , url: 'data/Branch_Type/', url_detail: 'data-detail/Branch_Type/', params:  {}},
    {name: 'branch', url: 'data/Branch/', url_detail: 'data-detail/Branch/', params:  {sort: 'index', values: 'id,signature,signature__code,signature__fullname,index,start_date,manager,manager__phone,manager__email,manager__fullname,phone,email,address,code,name,type,type__code,type__name,create_time'}},
  {name: 'loanproduct' , url: 'data/Loan_Product/', url_detail: 'data-detail/Loan_Product/', params:  {sort: '-id', values: 'id,principal,number_days,amount,collat_mandatory,penalty_info,penalty_rate,penalty_ratio,install_cycle_days,prin_cycle_days,itr_cycle_days,currency,currency__code,currency__rate,prin_pay_type,prin_pay_type__name,prin_cycle_days,itr_pay_type,itr_pay_type__name,itr_cycle_days,code,name,type,type__code,type__name,base,base__code,base__name,rate,unit,unit__name,ratio,creator,creator__fullname,create_time,update_time,rate_info,detail',distinct_values: {label: {type: 'Concat', field: ['code', 'name']}}, summary: 'annotate'}},
    {name: 'currency', url: 'data/Currency/', url_detail: 'data-detail/Currency/', params: {}},
  {name: 'defaultcurrency', url: 'data/Currency/', url_detail: 'data-detail/Currency/', params: {filter: {id: 1}}},
    {name: 'interestbase' , url: 'data/Interest_Base/', url_detail: 'data-detail/Interest_Base/', params:  {sort: 'index'}},
    {name: 'paymentmethod' , url: 'data/Payment_Method/', url_detail: 'data-detail/Payment_Method/', params:  {sort: 'name'}},
    {name: 'loantype' , url: 'data/Loan_Type/', url_detail: 'data-detail/Loan_Type/', params:  {}},
    {name: 'loanstatus' , url: 'data/Loan_Status/', url_detail: 'data-detail/Loan_Status/', params:  {}},
    {name: 'status', commit: 'status', url: 'data/Approve_Status/', url_detail: 'data-detail/Approve_Status/', params: {sort: 'index'}},
    {name: 'applicationstatus', url: 'data/Application_Status/', url_detail: 'data-detail/Application_Status/', params: {}},
    {name: 'executecommand', url: 'execute-command/', params: {}},
    {name: 'ssh', url: 'data/Ssh/', url_detail: 'data-detail/Ssh/', params: {filter: {deleted: 0}}},
    {name: 'sshlist', commit: 'updateSsh', url: 'data/Ssh/', url_detail: 'data-detail/Ssh/', params: {values: 'id,deleted,name,host,port,username,password,path,create_time,update_time', filter: {deleted: 0}, distinct_values: {label: {type: 'Concat', field: ['name', 'host']}}, summary: 'annotate'}},
    {
      name: "application",
      url: "data/Application/",
      url_detail: "data-detail/Application/",
      params: {
        values:
          "id,customer,customer__code,status,status__name,branch__code,country__code,currency__code,loan_amount,loan_term,code,fullname,phone,province,district,address,legal_type,legal_type__code,sex,sex__name,issue_place,loan_term,loan_amount,legal_type__name,legal_code,issue_date,issue_place,country,collaborator,create_time,update_time",
      }
    }
  ]

  const store = useStore()
  const { $copy, $clone, $updateSeriesFields, $snackbar, $remove, $dialog } = useNuxtApp()

  const requestLogin = function() {
    store.commit('login', undefined)
    window.location.href = `https://${mode==='dev'? '' : ''}utopialogin.dev247.net/signin?module=${module}&link=${window.location.origin}`
  }


  const getpath = function(name) {
    return name? paths.find(v=>v.name===name).url : path
  }
  const findapi = function(name) {
    const result = Array.isArray(name)? apis.filter(v=>name.findIndex(x=>v.name===x)>=0) : apis.find(v=>v.name===name)
    return $copy(result)
  }

  const readyapi = function(list) {
    var array = []
    list.forEach(element => {
      let found = apis.find(v=>v.name===element)
      if(found) {
        let ele = JSON.parse(JSON.stringify(found))
        ele.ready = store[element]? true : false
        array.push(ele)
      }
    })
   return array
  }

   // get data
  const getapi = async function(list) {
    try {
      let arr = list.map(v => {
        let found = apis.find(v=>v.name===v.name)
        let url = (v.path? paths.find(x=>x.name===v.path).url : path) + (v.url? v.url : found.url)
        let params = v.params? v.params : (found.params===undefined? {} : found.params)
        params.login = store.login? store.login.id : undefined 
        return {url: url, params: params}
      })
      //let data = await Promise.all(arr.map(v=>axios.get(v.url, {params: v.params})))
      let data = await Promise.all(arr.map(v => $fetch(v.url, { params: v.params })))
      data.map((v,i) => {
        list[i].data = v
        if(list[i].commit) {
          let data = v.rows? v.rows : v
          store.commit(list[i].commit, data)
        }   
      })
      return list
    }  catch(err) {
      console.log(err)
      return 'error'
    }
  }

  // insert data
  const insertapi = async function(name, data, values, notify) {
      try {
        let found = findapi(name)
        let curpath = found.path? paths.find(x=>x.name===found.path).url : path
        var rs
        if(!Array.isArray(data))
          rs = await axios.post(`${curpath}${found.url}`, data, {params: {values: values}})
        else {
          let params = {action: 'import', values: values}
          rs = await axios.post(`${curpath}import-data/${found.url.substring(5, found.url.length-1)}/`, data, {params: params})
        }
        // update store 
        if(found.commit) {
          if(store[found.commit]) {
            let copy = JSON.parse(JSON.stringify(store[found.commit]))
            let rows = Array.isArray(rs.data)? rs.data : [rs.data]
            rows.map(v=>{
              if(v.id && !v.error) {
                let idx = copy.findIndex(x=>x.id===v.id)
                if(idx>=0) copy[idx] = v
                else copy.push(v)
              }
            })
            store.commit(found.commit, copy)
          }
        }
        if(notify!==false) {
          store.lang===''? $snackbar('Dữ liệu đã được lưu vào hệ thống', 'Thành công', 'Success')
          : $snackbar(' The data has been saved to the system', 'Success', 'Success')
        }
        return rs.data
      } catch(err) {
        console.log(err)  
        return 'error'
      }
    }

    // update api
    const updateapi = async function(name, data, values, notify) {
      try {
        let found = findapi(name)
        let rs = await axios.put(`${path}${found.url_detail}${data.id}/`, data, {params: {values: values? values : found.params.values}})
        if(found.commit) {
          let index = store[found.commit]? store[found.commit].findIndex(v=>v.id===rs.data.id) : -1 
          if(index>=0) {
            var copy = JSON.parse(JSON.stringify(store[found.commit]))
            if(Array.isArray(rs.data)===false) copy[index] = rs.data
            else {
              rs.data.forEach(v => {
                let index = copy.findIndex(v=>v.id===v.id)
                if(index>=0) copy[index] = v
              })
            }
            store.commit(found.commit, copy)
          }
        }
        if(notify!==false) {
          store.lang==='vi'? $snackbar('Dữ liệu đã được lưu vào hệ thống', 'Thành công', 'Success')
          : $snackbar(' The data has been saved to the system', 'Success', 'Success')
        }
        return rs.data
      } catch(err) {
        console.log(err)  
        return 'error'
      }
    }

    const findpage = function(arr) {
      var copy = $copy(store.pagetrack)
      var doFind = function() {
        let found = undefined
        for (let i=1; i<=30; i++) {
          let name = `pagedata${i}`
          if(!copy[name]) {
            found = name
            copy[name] = true
            break;
          }
        }
        if(!found) console.log('pagename not found')
        return found
      }
      let result
      if(arr) {
        result = []
        arr.map(v=>{ result.push({name: v, value: doFind()})})
      } else {
        result = doFind(copy)
      }
      store.commit('pagetrack', copy)
      return result
    }

    const getpage = function(showFilter) {
      return {data: [], fields: [], filters: [], update: undefined, action: undefined, filterby: undefined, api: {full_data: true}, origin_api: {full_data: true}, 
      tablesetting: undefined, setting: undefined, tabfield: true, setpage: {}, showFilter: (!showFilter)? true : showFilter}
    }

    const setpage = function(pagename, row, api) {
      let json = row.detail
      let fields = $updateSeriesFields(json.fields)
      let copy = store[pagename] || getpage()
      copy.fields = fields
      copy.setting = $copy(row)
      if(json.filters) copy.filters = $copy(json.filters)
      if(json.tablesetting) copy.tablesetting = json.tablesetting
      if(api) {
        let copyApi = $copy(api)
        delete copyApi.data
        copyApi.full_data = api.data.full_data
        copyApi.total_rows = api.data.total_rows
        copy.api = copyApi
        copy.origin_api = copy
      }
      store.commit(pagename, copy)
      return copy
    }

    const getdata = async function(name, filter, params, first) {
      let found = findapi(name)
      if(params) found.params = params
      else if(filter) found.params.filter = filter
      let rs = await getapi([found])
      let data = rs[0].data
      if(data) {
        if(data.rows) {
          return first? (data.rows.length>0? data.rows[0] : undefined) : data.rows
        } else {
          let rows = Array.isArray(data)? data : [data]
          return first? (rows.length>0? rows[0] : data) : data
        }        
      } else {
        let rows = Array.isArray(data)? data : [data]
        return first? (rows.length>0? rows[0] : data) : data
      }
    }

    // insert row
    var insertrow = async function(name, data, values, pagename, notify) {
      let result = await insertapi(name, data, values, notify)
      if(result==='error' || !pagename) return result
      let arr = Array.isArray(result)? result : [result]
      //arr = $formatArray(arr, store[pagename].fields)
      let copy = $clone(store[pagename])
      arr.map(x=>{
        let index = copy.data.findIndex(v=>v.id===x.id)
        index>=0? copy.data[index] = x : copy.data.unshift(x)
      })
      copy.update = {data: copy.data}
      store.commit(pagename, copy)
      return result
    }

     // update row
    const updaterow = async function(name, data, values, pagename, notify) {
      let result = await updateapi(name, data, values, notify)
      if(result==='error' || !pagename) return result
      let arr = Array.isArray(result)? result : [result]
      //arr = $formatArray(arr, store[pagename].fields)
      let copy = $clone(store[pagename])
      arr.map(x=>{
        let index = copy.data.findIndex(v=>v.id===x.id)
        index>=0? copy.data[index] = x : copy.data.unshift(x)
      })
      copy.update = {data: copy.data}
      store.commit(pagename, copy)
      return result
    }

    // delete data
    const deleteapi = async function(name, id) {
      try {
        var rs
        let found = findapi(name)
        if(!Array.isArray(id))
          rs = await $fetch(`${path}${found.url_detail}${id}`, {method: 'delete'})
        else {
          let params = {action: 'delete'}
          rs = await $fetch(`${path}import-data/${found.url.substring(5,found.url.length-1)}/`, id, {params: params})
        }
        if(found.commit) {
          let copy = JSON.parse(JSON.stringify(store[found.commit]))
          if(!Array.isArray(id)) {
            let index = copy.findIndex(v=>v.id===id)
            if(index>=0) $remove(copy, index)
          } else  {
            rs.data.forEach(element => {
              let index = copy.findIndex(v=>v.id===element.id)
              if(index>=0) $remove(copy, index)
            })
          }
          store.commit(found.name, copy)
          console.log('copy', copy)
        }
        return id
      } catch(err) {
        console.log(err)
        if(err.response) {
          let content = `<span class="has-text-danger">Đã xảy ra lỗi, xóa dữ liệu không thành công</span>`
          if(err.response.data) content += `<p class="mt-2 has-text-grey-dark"> 
          <sapn class="icon-text">Chi tiết<SvgIcon class="ml-1" v-bind="{name: 'right.svg', type: 'dark', size: 20}"></SvgIcon></span></p>
          <p class="mt-2 has-text-grey-dark">${JSON.stringify(err.response.data)}</p>`
          $dialog(content, 'Lỗi', 'Error')
        }
        return 'error'
      }
    }

    // delete row
    const deleterow = async function(name, id, pagename) {
      let result = await deleteapi(name, id)
      let arr = Array.isArray(id)? id : [{id: id}]
      let copy = $clone(store[pagename])
      arr.map(x=>{
        let index = copy.data.findIndex(v=>v.id===x.id)
        index>=0? $remove(copy.data,index) : false
      })
      copy.update = {data: copy.data}
      store.commit(pagename, copy)
      return result
    }

     // update page
     const updatepage = function(pagename, row, action) { 
      let copy = $clone(store[pagename])
      let rows = Array.isArray(row)? row : [row]
      rows.map(x=>{
        let idx = copy.data.findIndex(v=>v.id===x.id)
        if(action==='delete') {
          if(idx>=0) $remove(copy.data, idx)
        } else {
          idx>=0? copy.data[idx] = x : copy.data.unshift(x) 
        }
      })
      copy.update = {data: copy.data}
      store.commit(pagename, copy)
    }

  return {
    provide: {
      getpath,
      findapi,
      readyapi,
      getapi,
      getdata,
      insertapi,
      updateapi,
      updaterow,
      findpage,
      getpage,
      setpage,
      insertrow,
      deleteapi,
      deleterow,
      updatepage,
      store,
      requestLogin
    }
  }
})

