package cn.com.ty.lift.system.settings.controller;


import cn.com.ty.lift.system.settings.dao.entity.GlobalSet;
import cn.com.ty.lift.system.settings.service.impl.GlobalSetServiceImpl;
import cn.com.xwy.boot.web.dto.RestResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 全局设置 前端控制器
 * </p>
 *
 * @author wang-hai-cheng
 * @since 2019-12-13
 */
@RestController
@RequestMapping("/set")
@AllArgsConstructor
public class GlobalSetController {
    private final GlobalSetServiceImpl globalSetService;

    /**
     * 获取维保公司的全局设置列表
     *
     * @param globalSet 维保公司id
     * @return 操作结果
     * @since 2019/12/13 16:23
     */
    @PostMapping("/list")
    public RestResponse sets(@RequestBody GlobalSet globalSet) {
        List<Map<String, Object>> globalSets = globalSetService
                .listMaps(new QueryWrapper<GlobalSet>()
                        .select("code", "value")
                        .eq("company_id", globalSet.getCompanyId()));
        if (globalSets.isEmpty()) {
            return RestResponse.success();
        }
        HashMap<String, Object> result = new HashMap<>();
        result.put("companyId", globalSet.getCompanyId());
        HashMap<String, Object> tempMap = new HashMap<>();
        globalSets.forEach(gs -> {
            tempMap.put(gs.get("code").toString(), gs.get("value"));
        });
        result.put("sets", tempMap);
        return RestResponse.success(result, "成功");
    }

    /**
     * 根据id更新维保公司的全局设置
     *
     * @param req 要修改的数据
     * @return 操作结果
     * @since 2019/12/13 16:24
     */
    @PostMapping("/modify")
    public RestResponse modify(@RequestBody Map<String, Object> req) {
        Long companyId = Long.valueOf(req.get("companyId").toString());
        HashMap<String, Object> sets = (HashMap<String, Object>) req.get("sets");
        List<GlobalSet> globalSets = globalSetService.list(new QueryWrapper<GlobalSet>().eq("company_id", companyId));
        sets.forEach((k, v) -> {
            for (GlobalSet globalSet : globalSets) {
                if (globalSet.getCode().equals(k))
                    globalSet.setValue(Integer.valueOf(v.toString()));
            }
        });
        //更新redis数据
        globalSetService.saveToRedis(globalSets, companyId);
        //更新mysql数据
        if (globalSetService.updateBatchById(globalSets)) {
            return RestResponse.success(null, "成功");
        }
        return RestResponse.success();
    }
}