package cn.iocoder.yudao.module.system.controller.admin.user;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.smartfactory.api.factoryInfo.FactoryInfoApi;
import cn.iocoder.yudao.module.smartfactory.api.factoryInfo.dto.FactoryInfoDTO;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.factoryUser.FactoryUserPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.factoryUser.FactoryUserRespVO;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.factoryUser.FactoryUserSaveReqVO;
import cn.iocoder.yudao.module.system.convert.user.FactoryUserConvert;
import cn.iocoder.yudao.module.system.dal.dataobject.dept.DeptDO;
import cn.iocoder.yudao.module.system.dal.dataobject.dict.DictDataDO;
import cn.iocoder.yudao.module.system.dal.dataobject.equipment.UsersExtDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.service.dept.DeptService;
import cn.iocoder.yudao.module.system.service.dict.DictDataService;
import cn.iocoder.yudao.module.system.service.equipment.UsersExtService;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import cn.iocoder.yudao.module.system.service.user.FactoryUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.error;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertMap;

@Tag(name = "管理后台 - 工厂用户")
@RestController
@RequestMapping("/system/factory-user")
@Validated
public class FactoryUserController {

    @Resource
    private FactoryUserService factoryUserService;

    @Resource
    private AdminUserService userService;

    @Resource
    @Lazy
    private DeptService deptService;

    @Resource
    private DictDataService dictDataService;

    @Resource
    @Lazy
    private UsersExtService usersExtService;

    @Resource
    private FactoryInfoApi factoryInfoApi;

    @PostMapping(value = "/create")
    @Operation(summary = "新增工厂用户")
    @PreAuthorize("@ss.hasPermission('system:factory-user:create')")
    public CommonResult<String> createUser(@RequestBody FactoryUserSaveReqVO reqVO) {

        String msg = factoryUserService.createUser(reqVO);

        if (msg == null) {

            return success("true");
        }else {

            return error(-1, "照片下发异常！");
        }
    }

    @PutMapping(value = "/update")
    @Operation(summary = "修改工厂用户")
    @PreAuthorize("@ss.hasPermission('system:factory-user:update')")
    public CommonResult<String> updateUser(@RequestBody FactoryUserSaveReqVO reqVO) {

        String msg = factoryUserService.updateUser(reqVO);

        if (msg == null) {

            return success("true");
        }else {

            return error(-1, msg);
        }
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除工厂用户")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('system:factory-user:delete')")
    public CommonResult<String> deleteUser(@RequestParam("id") Long id) {

        String msg = factoryUserService.deleteUser(id);
        if (msg == null) {

            return success("true");
        }else {

            return error(-1, msg);
        }
    }

    @GetMapping("/get")
    @Operation(summary = "获得工厂用户详情")
    @Parameter(name = "id", description = "编号", required = true, example = "146")
    @PreAuthorize("@ss.hasPermission('system:factory-user:query')")
    public CommonResult<FactoryUserRespVO> getUser(@RequestParam("id") Long id) {

        AdminUserDO user = userService.getUser(id);

        // 获得部门信息
        DeptDO deptDO = deptService.getDept(user.getDeptId());

        // 获得工厂信息
        FactoryInfoDTO factoryInfoDTO = factoryInfoApi.getFactoryInfo(deptDO.getFactoryId()).getCheckedData();

        // 获得拓展信息
        UsersExtDO usersExtDO = usersExtService.getUsersExtByUserId(user.getId());

        // 获得工种 字典信息
        DictDataDO dictDataDO = dictDataService.getDictData("user_work_type", String.valueOf(usersExtDO.getWorkType()));

        return success(FactoryUserConvert.INSTANCE.convert(user, factoryInfoDTO, dictDataDO, usersExtDO));
    }

    @GetMapping("/page")
    @Operation(summary = "获得工厂用户分页列表")
    @PreAuthorize("@ss.hasPermission('system:factory-user:query')")
    public CommonResult<PageResult<FactoryUserRespVO>> getUserPage(@Valid FactoryUserPageReqVO pageReqVO) {

        // 获得用户分页列表
        PageResult<AdminUserDO> pageResult = userService.getFactoryUserPage(pageReqVO);

        if (pageResult.getList() == null || pageResult.getList().isEmpty()) {
            return success(new PageResult<>(new ArrayList<>(), 0L));
        }

        // 部门信息
        List<DeptDO> deptDOs = deptService.getDeptList(convertList(pageResult.getList(), AdminUserDO::getDeptId));
        // 获得工厂信息
        List<FactoryInfoDTO> factoryInfoDTOS = factoryInfoApi.getFactoryInfoList(convertList(deptDOs, DeptDO::getFactoryId)).getCheckedData();
        Map<Long, FactoryInfoDTO> factoryInfoMap = new HashMap<>();
        if (factoryInfoDTOS != null && !factoryInfoDTOS.isEmpty()) {

            factoryInfoMap = deptDOs.stream()
                    .collect(Collectors.toMap(DeptDO::getId,
                            dept -> factoryInfoDTOS.stream().
                                    filter(info -> info.getId().equals(dept.getFactoryId()))
                                    .findFirst().orElseGet(FactoryInfoDTO::new)));
        }

        // 获得拓展信息
        List<UsersExtDO> usersExtDOS = usersExtService.getListByUserId(convertList(pageResult.getList(), AdminUserDO::getId));
        Map<Long, UsersExtDO> usersExtDOMap = convertMap(usersExtDOS, UsersExtDO::getUserId);

        // 获得工种 字典信息
        List<String> workTypes = usersExtDOS.stream().map(info -> info.getWorkType().toString()).collect(Collectors.toList());
        List<DictDataDO> dictDataDO = dictDataService.getDictDataList("user_work_type", workTypes);

        // 获得工种MAP
        Map<String, DictDataDO> dictDataMap = convertMap(dictDataDO, DictDataDO::getValue);

        return success(new PageResult<>(FactoryUserConvert.INSTANCE.convertList(pageResult.getList(), factoryInfoMap, dictDataMap, usersExtDOMap),
                pageResult.getTotal()));
    }
}
