import com.sdtool.business.dao.MallDao
import com.sdtool.common.api.BusinessExecutor
import com.sdtool.common.api.mall.MallAdminService
import com.sdtool.common.datas.ERPModule
import com.sdtool.common.entity.base.InvokeCallParams
import com.sdtool.common.entity.base.InvokeCallResult
import com.sdtool.common.entity.mall.MallUser
import com.dySweetFishPlugin.sql.dao.OperatorWait
import com.dySweetFishPlugin.sql.dao.TunaService
import com.dySweetFishPlugin.tool.crypto.EncryptUtil
import com.sweetfish.convert.json.JsonConvert
import com.sweetfish.service.RetResult
import groovy.json.JsonSlurper
import org.rex.RMap

import javax.annotation.Resource


class BE_MallAdmin_ResetUserPwd implements BusinessExecutor<InvokeCallParams, InvokeCallResult> {

    @Resource
    TunaService tunaService

    @Resource
    JsonConvert jsonConvert

    @Resource
    MallAdminService mallAdminService

    @Resource(name = "property.passwordSalt")
    private String passwordSalt

    private MallDao mallDao

    @Override
    String scriptName() {
        return "商城后台8080-初始化用户密码"
    }

    @Override
    ERPModule module() {
        return ERPModule.MALL_ADMIN
    }

    @Override
    void start(long supplierCode) {
        mallDao = tunaService.generate(MallDao.class)
    }

    @Override
    boolean needLogin(InvokeCallParams source) {
        return true
    }

    @Override
    OperatorWait getAWait(InvokeCallParams s) {
        return OperatorWait.ASNYC
    }

    @Override
    RetResult<InvokeCallParams> checkExecute(InvokeCallParams source) {
        def jsonSlurper = new JsonSlurper()
        def invokeData = jsonSlurper.parseText(source.params)

        long idMallUser = invokeData["id"] as long
        MallUser mallUser = mallAdminService.getRedisMallUser(idMallUser, source.supplierCode)
        if (mallUser == null) {
            return RetResult.<InvokeCallParams> errorT().retinfo("无效的用户信息")
        }

        return RetResult.<InvokeCallParams> successT().result(source)
    }

    @Override
    RetResult<InvokeCallResult> execute(InvokeCallParams source) {
        def jsonSlurper = new JsonSlurper()
        def invokeData = jsonSlurper.parseText(source.params)

        long idMallUser = invokeData["id"] as long
        MallUser mallUser = mallAdminService.getRedisMallUser(idMallUser, source.supplierCode)

        RMap paramMap = new RMap()
        paramMap.put("linkedAccount", mallUser.loginAccount)
        paramMap.put("linkedPassword", EncryptUtil.md5Digest(mallUser.loginAccount + passwordSalt))
        mallDao.resetMallUserPassword(paramMap, source.dataSourceId, source.supplierCode)

        return RetResult.<InvokeCallResult> successT().result(InvokeCallResult.success())
    }
}

