package com.yccrc.kede.controller.admin;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yccrc.common.annotation.Log;
import com.yccrc.common.constant.UserConstants;
import com.yccrc.common.core.controller.BaseController;
import com.yccrc.common.core.domain.entity.SysUser;
import com.yccrc.common.enums.BusinessType;
import com.yccrc.common.utils.SecurityUtils;
import com.yccrc.common.vo.Result;
import com.yccrc.kede.domain.Enterprise;
import com.yccrc.kede.domain.EnterpriseLog;
import com.yccrc.kede.enums.UserTypeEnum;
import com.yccrc.kede.service.IEnterpriseLogService;
import com.yccrc.kede.service.IEnterpriseService;
import com.yccrc.kede.service.INotifyService;
import com.yccrc.kede.vo.EnterpriseAdminVO;
import com.yccrc.kede.vo.EnterpriseAuthVO;
import com.yccrc.system.service.ISysConfigService;
import com.yccrc.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;


/**
 * 企业信息Controller
 *
 * @author yccrc
 * @date 2022-04-25
 */
@Api(tags = "企业信息")
@RestController
@RequestMapping("/admin/enterprise")
public class EnterpriseAdminController extends BaseController {

    @Autowired
    private IEnterpriseService enterpriseService;


    @Autowired
    private ISysUserService userService;

    @Autowired
    ISysConfigService configService;

    @Autowired
    INotifyService notifyService;

    @Autowired
    private IEnterpriseLogService enterpriseLogService;

    @ApiOperation(value = "查询企业信息列表")
    @GetMapping("/list")
    public Result<Page<Enterprise>> list(Enterprise enterprise) {
        Page<Enterprise> page = enterpriseService.selectEnterprise(enterprise);
//    	if(!CollectionUtil.isEmpty(page.getRecords())) {
//    		for(Enterprise e:page.getRecords()) {
//    			e.setProvinceName(regionService.getNameById(e.getProvinceId()));
//    			e.setCityName(regionService.getNameById(e.getCityId()));
//    			e.setDistrictName(regionService.getNameById(e.getDistrictId()));
//    		}
//    	}

        return new Result<Page<Enterprise>>().ok(page);

    }

    @ApiOperation(value = "获取企业信息详细信息")
    @GetMapping(value = "/{id}")
    public Result<Enterprise> getInfo(@PathVariable("id") Integer id) {
        return new Result<Enterprise>().ok(enterpriseService.getById(id));
    }


    @ApiOperation(value = "新增企业信息")
    @Log(title = "企业信息", businessType = BusinessType.INSERT)
    @PostMapping("save")
    public Result<Boolean> add(@RequestBody EnterpriseAdminVO enterprise) {
        enterprise.setCreateBy(super.getUsername());
        enterprise.setEntState(2);
        enterprise.setAuthState(2);
        return new Result<Boolean>().ok(enterpriseService.saveAdminEnterprise(enterprise));
    }

    @ApiOperation(value = "企业审核")
    @Log(title = "企业审核", businessType = BusinessType.UPDATE)
    @PostMapping("auth")
    public Result<Boolean> auth(@RequestBody EnterpriseAuthVO body) {
        logger.info("企业审核信息:{}", JSON.toJSONString(body));
        notifyService.authEnterpriseMsg(body);
        // 同步企业名称、手机号、邮箱到用户表中
        Enterprise enterprise = enterpriseService.getById(body.getId());
        userService.lambdaUpdate()
                .set(SysUser::getNickName, enterprise.getEntName())
                .set(SysUser::getPhonenumber, enterprise.getLinkMobile())
                .set(SysUser::getEmail, enterprise.getLinkEmail())
                .eq(SysUser::getScopeId, enterprise.getId()).update();

        return new Result<Boolean>().ok(enterpriseService.lambdaUpdate()
                .set(Enterprise::getAuthState, body.getAuthState())
                .set(body.getAuthState() == 2, Enterprise::getEntState, 2) //审核通过 服务中
                .set(!StrUtil.isEmpty(body.getStartDate()), Enterprise::getStartDate, body.getStartDate())
                .set(!StrUtil.isEmpty(body.getEndDate()), Enterprise::getEndDate, body.getEndDate())
                .eq(Enterprise::getId, body.getId()).update());
    }

    @ApiOperation(value = "修改企业信息")
    @Log(title = "企业信息", businessType = BusinessType.UPDATE)
    @PutMapping("update")
    public Result<Boolean> edit(@RequestBody Enterprise enterprise) {
        return new Result<Boolean>().ok(enterpriseService.updateById(enterprise));
    }

    @ApiOperation(value = "修改服务时间")
    @Log(title = "修改服务时间", businessType = BusinessType.UPDATE)
    @PutMapping("modifyServiceTime")
    public Result<Boolean> modifyServiceTime(@RequestBody Enterprise enterprise) {
        return new Result<Boolean>().ok(enterpriseService.modifyServiceTime(enterprise));
    }

    @ApiOperation(value = "获取服务时间修改记录")
    @GetMapping(value = {"/getModifyServiceTimeList/{enterpriseId}"})
    public Result<List<EnterpriseLog>> getModifyServiceTimeList(@PathVariable(value = "enterpriseId") Integer enterpriseId) {
        return new Result<List<EnterpriseLog>>().ok(enterpriseLogService.lambdaQuery().eq(EnterpriseLog::getEnterpriseId, enterpriseId).list());
    }

    @ApiOperation(value = "删除企业信息")
    @Log(title = "企业信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public Result<Boolean> remove(@PathVariable Integer[] ids) {
        return new Result<Boolean>().ok(enterpriseService.removeBatchByIds(Arrays.asList(ids)));
    }

    @ApiOperation(value = "重置密码")
    @PutMapping("/resetPwd/{id}")
    public Result<Boolean> resetPwd(@PathVariable("id") Integer id) {
        SysUser user = userService.lambdaQuery().eq(SysUser::getScopeId, id).eq(SysUser::getUserType, UserTypeEnum.ENT_ADMIN).one();
        //  userService.checkUserDataScope(user.getUserId());
        user.setPassword(SecurityUtils.encryptPassword(configService.selectConfigByKey("sys.user.initPassword")));
        user.setUpdateBy(getUsername());
        userService.resetPwd(user);
        return new Result<Boolean>().ok(true);
    }

    @ApiOperation(value = "停用")
    @PutMapping("/stop/{id}")
    public Result<Boolean> stop(@PathVariable("id") Integer id) {
        enterpriseService.lambdaUpdate().set(Enterprise::getEntState, 4).eq(Enterprise::getId, id).update();
        userService.lambdaUpdate().set(SysUser::getStatus, UserConstants.USER_DISABLE).eq(SysUser::getScopeId, id).update();
        return new Result<Boolean>().ok(true);
    }

    @ApiOperation(value = "启用")
    @PutMapping("/enable/{id}")
    public Result<Boolean> enable(@PathVariable("id") Integer id) {
        enterpriseService.lambdaUpdate().set(Enterprise::getEntState, 2).eq(Enterprise::getId, id).update();
        userService.lambdaUpdate().set(SysUser::getStatus, UserConstants.NORMAL).eq(SysUser::getScopeId, id).update();
        return new Result<Boolean>().ok(true);
    }

    @ApiOperation(value = "提醒")
    @PutMapping("/remind/{id}")
    public Result<Boolean> remind(@PathVariable("id") Integer id) {
        Enterprise enterprise = enterpriseService.getById(id);
        if (enterprise != null) {
            notifyService.expiredEnterpriseMsg(enterprise, false);
        }
        return new Result<Boolean>().ok(true);
    }

    /**
     * 根据用户编号获取详细信息
     */
    @ApiOperation(value = "获取用户信息")
    @GetMapping(value = {"/userInfo/{userId}"})
    public Result<SysUser> getInfo(@PathVariable(value = "userId") Long userId) {

        return new Result<SysUser>().ok(userService.getById(userId));
    }
}
