import com.sdtool.business.dao.LoginDao
import com.sdtool.business.dao.MallDao
import com.sdtool.common.api.BusinessExecutor
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.sdtool.common.entity.site.ERPTokenUser
import com.dySweetFishPlugin.sql.dao.OperatorWait
import com.dySweetFishPlugin.sql.dao.TunaService
import com.dySweetFishPlugin.tool.crypto.EncryptUtil
import com.sweetfish.service.RetResult
import groovy.json.JsonSlurper
import org.rex.RMap

import javax.annotation.Resource

/**
 * @Author: xl Created on 2024-03-27
 * @Content:
 */
class BE_MallUser_ChangePassword implements BusinessExecutor<InvokeCallParams, InvokeCallResult> {

    @Resource
    TunaService tunaService

    private MallDao mallDao

    private LoginDao loginDao

    /**
     * 密码盐
     */
    @Resource(name = "property.passwordSalt")
    private String passwordSalt

    @Override
    String scriptName() {
        return "购物商城-用户修改密码"
    }

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

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

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

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

    @Override
    RetResult<InvokeCallResult> execute(InvokeCallParams source) {
        String dataSourceId = source.dataSourceId
        long supplierCode = source.supplierCode
        ERPTokenUser currentUser = source.currentUser
        def jsonSlurper = new JsonSlurper()
        def invokeData = jsonSlurper.parseText(source.params)
        String newPassword = invokeData["newPassword"]
        String oldPassword = invokeData["oldPassword"]

        if (currentUser == null) {
            return RetResult.<InvokeCallResult> errorT().retinfo("未登录")
        }

        RMap paramMap = new RMap()
        String md5Password = EncryptUtil.md5Digest(oldPassword + passwordSalt)
        paramMap.put("id", currentUser.id)
        paramMap.put("loginName", currentUser.getAccount())
        paramMap.put("password", md5Password)

        MallUser destUser = loginDao.mallLogin(paramMap, dataSourceId, supplierCode)
        if (destUser == null) {
            return RetResult.<InvokeCallResult> errorT().retinfo("账号或原密码错误")
        }

        paramMap.put("newPassword", EncryptUtil.md5Digest(newPassword + passwordSalt))
        mallDao.editMallLoginUserPassword(paramMap, dataSourceId, supplierCode)
        return RetResult.<InvokeCallResult> successT().result(InvokeCallResult.success())
    }

}
