import vue from '@/main'
interface PageData {
    [key: string]: any
}
interface FileData {
    fileName: string;
    fileHash: string;
    file: File;
    type: string;
    fileUrl: string;
    fileSize: number
}
const rawData = [
    {
       trace: '',
       fileList:[],
       commissionFileList:[]
    },
    {
       proofName:'',
       proofType: '',
       proofFeature: '',
       proofDesc: '',
       proofCreateProgress: '',
       proofFinishDate: '',
       proofFinishPlace: [],
       proofPublishStatus: 0,
       proofPublishDate: '',
       proofPublishPlace: [],
    },
    {
       authGetWay: '',
       uploadAuthCer: [],
       authBelongWay: '',
       authBelongCer: [],
       authGuaranteeCer: [],
    },
    {
       copyrightOwnerList: [],
       authorList: [],
       rightSelectType: 0,
       rightList: [],
    }
]
const cprData = {
    needGetDraft: false, /**用来判断是否需要获取草稿 */
    draft:"",/**草稿，eachPageData的json字符串，用来对比数据是否改变 */
    currentStep: 1,
    rawPageData: JSON.parse(JSON.stringify(rawData)) as Array<PageData>,/**原始数据，用来对比数据是否改变 */
    eachPageData: JSON.parse(JSON.stringify(rawData)) as Array<PageData>,/**操作的数据 */
    allCprOwnerList: [] as any,
} 

export type copyrightStateType = typeof cprData
export const copyright = {
    namespaced: true,
    state(){
        return JSON.parse(JSON.stringify(cprData))
    },
    mutations: {
        /**草稿保存完或者版权申请完后还原数据 */
        resetAllData(state: copyrightStateType){
            Object.assign(state, JSON.parse(JSON.stringify(cprData)))
        },
        /**编辑或获取草稿的时候, 服务器有数据，初始化服务器的数据 */
        initEachPageData(state: copyrightStateType, payload: any){
            if(typeof payload == 'string') {
                state.draft = payload
                state.eachPageData = JSON.parse(payload)
                state.needGetDraft = true
            } else {
                state.currentStep = payload.step
                state.draft = payload.content
                state.eachPageData = JSON.parse(payload.content)
                state.needGetDraft = true
            }
        },
        /**改变当前步骤 */
        changeCurrentStep(state: copyrightStateType, payload: number){
            state.currentStep = payload
            console.log(payload)
        },
        /**第一步的存证选择框 */
        firstPageSelected(state: copyrightStateType, payload: any){
            state.eachPageData[0].trace = payload
        },
        /**第一步的上传文件后添加地址 */
        addUrlFirstPageFileList(state: copyrightStateType, payload: {fileHash: string, fileUrl: string, type: string}){
            state.eachPageData[0].fileList.forEach((item: FileData, key: number)=>{
                if(item.fileHash == payload.fileHash){
                    state.eachPageData[0].fileList[key].fileUrl = payload.fileUrl
                }
            })
        },
        /**第一步的上传和删除文件 */
        updataFirstPageFileList(state: copyrightStateType, fileDataOrHash: FileData | string){
          /**传入的是对象则是新增文件 */
          if(typeof fileDataOrHash == 'object') {
             if((state.eachPageData[0].fileList as Array<FileData>).length >= 5 ){
                vue.$toast('最多上传5个文件')
                return
             }
             (state.eachPageData[0].fileList as Array<FileData>).push(fileDataOrHash)
          /**传入单个hash则是删除指定hash文件 */
          }else if(typeof fileDataOrHash == 'string') {
             const fileListAfterDelete = (state.eachPageData[0].fileList as Array<FileData>).filter((item)=>{
                return item.fileHash != fileDataOrHash
             })
             state.eachPageData[0].fileList = fileListAfterDelete
          }
        },
        /**第一页作品登记代理委托书 */
        addUrlCommissionFileList(state: copyrightStateType, payload: {fileHash: string, fileUrl: string, type: string}){
            state.eachPageData[0].commissionFileList.forEach((item: FileData, key: number)=>{
                if(item.fileHash == payload.fileHash){
                    state.eachPageData[0].commissionFileList[key].fileUrl = payload.fileUrl
                }
            })
        },
        updataCommissionFileList(state: copyrightStateType, fileDataOrHash: FileData | string){
          /**传入的是对象则是新增文件 */
          if(typeof fileDataOrHash == 'object') {
            if((state.eachPageData[0].commissionFileList as Array<FileData>).length >= 1 ){
               vue.$toast('最多上传1个文件')
               return
            }
            (state.eachPageData[0].commissionFileList as Array<FileData>).push(fileDataOrHash)
         /**传入单个hash则是删除指定hash文件 */
         }else if(typeof fileDataOrHash == 'string') {
            const fileListAfterDelete = (state.eachPageData[0].commissionFileList as Array<FileData>).filter((item)=>{
               return item.fileHash != fileDataOrHash
            })
            state.eachPageData[0].commissionFileList = fileListAfterDelete
         }
        },



        /**更新第二步的数据 */
        updataSecondPageData(state: copyrightStateType, payload: {value: any, type: string}){
            /**如果发表状态时未发表，那清除发表日期和地点 */
            if(payload.type == 'proofPublishStatus' && payload.value == 1) {
                state.eachPageData[1].proofPublishDate = ''
                state.eachPageData[1].proofPublishPlace = []
            }
            state.eachPageData[1][payload.type] = payload.value
        },


        /**更新第三步的数据 */
        updataThirdPageData(state: copyrightStateType, payload: {value: FileData | string, type: string}){
           /**上传数据 */
           if(['authGetWay', 'authBelongWay'].indexOf(payload.type) != -1){
              state.eachPageData[2][payload.type] = payload.value
           }else if(['uploadAuthCer', 'authBelongCer', 'authGuaranteeCer'].indexOf(payload.type) != -1){
              /**传入的是对象则是新增文件*/
              if(typeof payload.value == 'object') {
                 if(state.eachPageData[2][payload.type].length >= 1){
                    vue.$toast('最多上传1个文件')
                    return
                 }
                 state.eachPageData[2][payload.type].push(payload.value)
              /**传入单个hash则是删除指定hash文件*/
              }else if(typeof payload.value == 'string') {
                 const fileListAfterDelete = state.eachPageData[2][payload.type].filter((item: FileData)=>{
                    return item.fileHash != payload.value
                 })
                 state.eachPageData[2][payload.type] = fileListAfterDelete
              }
           }
        },
        /**第三步上传完文件后更新文件路径 */
        onAddCerFileUrl(state: copyrightStateType, payload: {type: string, value: {fileHash: string, fileUrl: string}}){
            state.eachPageData[2][payload.type][0].fileUrl = payload.value.fileUrl
        },


        /**更新第四步的数据 */
        /**删除著作权人,这里的删除其实只是不选择 */
        onDeleteCopyrightOwner(state: copyrightStateType, id: any){
            state.eachPageData[3].copyrightOwnerList = state.eachPageData[3].copyrightOwnerList.filter((item:any)=>{
                return item.id != id
            })
        },
        /**添加作者 */
        onAddAuthor(state: copyrightStateType, payload: any){
            state.eachPageData[3].authorList.push(payload)
        },
        /**更改作者信息 */
        onAuthorDataChange(state: copyrightStateType, payload: {id: number, name?: string, alias?: string, aliasType?: any, type: 'name' | 'alias' | 'aliasType'}){
            state.eachPageData[3].authorList = state.eachPageData[3].authorList.map((item: {id: number, name: string, alias: string, aliasType: any})=>{
                if(item.id == payload.id){
                    item[payload.type] = payload[payload.type]
                    return item
                }else {
                    return item
                }
            })
        },
        /**删除作者 */
        onDeleteAuthorData(state: copyrightStateType, id: number){
            state.eachPageData[3].authorList = state.eachPageData[3].authorList.filter((item: {id: number, name: string, alias: string, aliasType: any})=>{
                return item.id != id
            })
        },
        /**改变权利选择类型, 0-全部，1-部分 */
        changeRightSelectType(state: copyrightStateType, rightSelectType: number){
            state.eachPageData[3].rightSelectType = rightSelectType
        },
        /**改变权利列表 */
        changeRightList(state: copyrightStateType, rightList: Array<{name: string, selected: true}>){
            state.eachPageData[3].rightList = rightList
        },
        /**改变步骤 */
        changeStep(state: copyrightStateType, payload: number){
            state.currentStep += payload
        },


        /**新增著作权人数据也要保存到store中 */
        /**每次初始化获取著作权人列表，都从服务器获取一次 */
        changeAllCprOwnerList(state: copyrightStateType, list: any){
            state.allCprOwnerList = list
        },
        /**删除著作权人，同时需要删除后端的数据 */
        onDeleteallCprOwnerList(state: copyrightStateType, id: number){
             state.allCprOwnerList = state.allCprOwnerList.filter((item:any)=>{
                return item.id != id
             })
        },
        /**改变选择状态*/
        changeSelectedallCprOwnerList(state: copyrightStateType, id: number){
            state.allCprOwnerList = state.allCprOwnerList.map((item: any)=>{
                if(item.id == id) {
                    return {...item, selected: !item.selected}
                }
                return {...item}
                
            })
        },
        /**确认选择完著作权人后,把临时列表给最终列表 */
        comfirmCprOwner(state: copyrightStateType){
            state.eachPageData[3].copyrightOwnerList = state.allCprOwnerList.filter((item:any)=>{
                return item.selected
            })
        }
    },
    actions: {
        /**每次重选择版权人信息的时候，需要获取一次全部版权人，并且根据第四步的选择状态更改每个的选中状态 */
        async getAllCprOwnerList({commit, state}: any){
            const ownerList = await vue.$service.copyrightService.getCopyrightOwnerList()
            for(let item of ownerList) {
                for(let i of state.eachPageData[3].copyrightOwnerList) {
                    if(i.id == item.id){
                        item.selected = true
                    }
                }
            }
            commit('changeAllCprOwnerList', ownerList)
        }
    },
    getters: {},
}
