package com.sw.mes.yb.deviceCheck.controller;

import com.sw.mes.core.response.ResponsePage;
import com.sw.mes.core.response.Result;
import com.sw.mes.core.response.ResultGenerator;
import com.sw.mes.base.system.service.DictionaryItemService;
import com.sw.mes.core.utils.DynamicSpecifications;
import com.sw.mes.core.utils.RequestPage;
import com.sw.mes.yb.deviceCheck.entity.SpotCheckItem;
import com.sw.mes.yb.deviceCheck.service.SpotCheckItemService;
import com.sw.mes.yb.deviceCheck.service.SpotCheckService;
import com.sw.mes.yb.deviceCheck.entity.SpotCheck;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/pc/spotCheck")
@Slf4j
@Api(description = "点检项目接口")
public class SpotCheckController {

    @Autowired
    private SpotCheckService spotCheckService;

    @Autowired
    private SpotCheckItemService spotCheckItemService;

    @Autowired
    private DictionaryItemService dictionaryItemService;

    @ApiOperation(value = "创建点检项目")
    @RequestMapping(value="/create", method= RequestMethod.POST)
    public @ResponseBody
    Result create(@RequestBody @Valid SpotCheck spotCheck) {

        SpotCheck org = spotCheckService.getByName(spotCheck.getName());
        if(org != null) {
            return ResultGenerator.fail("该点检项目名称已存在");
        }
        spotCheckService.saveOrUpdate(spotCheck);

        List<SpotCheckItem> itemList = spotCheck.getItemList();
        if(itemList != null && itemList.size() > 0) {
            for (SpotCheckItem item: itemList) {
                item.setParentId(spotCheck.getId());
                item.setParent(spotCheck.getName());
            }
            spotCheckItemService.saveInBatch(itemList);
        }
        return ResultGenerator.success();
    }

    @ApiOperation(value = "点检项目详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "点检项目ID", paramType = "path", dataType = "Integer"),
    })
    @RequestMapping(value="/update/{id}", method= RequestMethod.GET)
    public Result preUpdate(@PathVariable Integer id) {
        SpotCheck spotCheck = spotCheckService.get(id);
        List<SpotCheckItem> itemList = spotCheckItemService.findByParentId(id);
        spotCheck.setItemList(itemList);
        return ResultGenerator.success(spotCheck);
    }

    @ApiOperation(value = "更新点检项目")
    @RequestMapping(value="/update", method= RequestMethod.POST)
    public @ResponseBody
    Result update(@Valid @RequestBody SpotCheck spotCheck) {

        SpotCheck org = spotCheckService.getByName(spotCheck.getName());
        if(org != null && !org.getId().equals(spotCheck.getId())) {
            return ResultGenerator.fail("该点检项目名称已存在");
        }
        spotCheckService.saveOrUpdate(spotCheck);

        Map<Integer, SpotCheckItem> itemMap = new HashMap<>();
        List<SpotCheckItem> orgList = spotCheckItemService.findByParentId(spotCheck.getId());
        if (orgList != null && orgList.size() > 0) {
            for (SpotCheckItem item: orgList) {
                itemMap.put(item.getId(), item);
            }
        }

        List<SpotCheckItem> itemList = spotCheck.getItemList();
        if(itemList != null && itemList.size() > 0) {
            for (SpotCheckItem item: itemList) {
                item.setParent(spotCheck.getName());
                item.setParentId(spotCheck.getId());
                if (itemMap.containsKey(item.getId())) {
                    itemMap.remove(item.getId());
                }
            }
            spotCheckItemService.saveInBatch(itemList);
        }
        if (itemMap.size() > 0) {
            List<SpotCheckItem> del = new ArrayList<>(itemMap.values());
            for (SpotCheckItem d: del) {
                spotCheckItemService.delete(d.getId());
            }
        }
        return ResultGenerator.success();
    }

    @RequestMapping(value="/delete/{id}", method= RequestMethod.POST)
    public @ResponseBody
    Result delete(@PathVariable Integer id) {
        spotCheckService.delete(id);
        spotCheckItemService.deleteByParentId(id);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "删除点检项目")
    @ApiImplicitParams({
    })
    @RequestMapping(value="/delete", method= RequestMethod.POST)
    public @ResponseBody
    Result deleteMany(@ApiParam(value = "id集合,逗号分隔,如2,4", type = "query") @RequestParam Integer[] ids) {
        for (int i = 0; i < ids.length; i++) {
            SpotCheck spotCheck = spotCheckService.get(ids[i]);
            if (spotCheck != null) {
                spotCheckService.delete(spotCheck.getId());
                spotCheckItemService.deleteByParentId(spotCheck.getId());
            }
        }
        return ResultGenerator.success();
    }

    @ApiOperation(value = "分页查询点检项目列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "search_LIKE_name", value = "点检项目", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_LIKE_type", value = "点检类型", dataType = "string", paramType = "query")
    })
    @RequestMapping(value="/list", method= RequestMethod.GET)
    public Result<ResponsePage<SpotCheck>> list(ServletRequest request, RequestPage page) {
        Specification<SpotCheck> specification = DynamicSpecifications.bySearchFilter(request, SpotCheck.class);
        List<SpotCheck> spotChecks = spotCheckService.findByExample(specification, page);

        ResponsePage responsePage = new ResponsePage(spotChecks,page.getTotal());
        return ResultGenerator.success(responsePage);
    }

    @ApiOperation(value = "点检项目详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "点检项目ID", paramType = "path", dataType = "Integer"),
    })
    @RequestMapping(value="/view/{id}", method= RequestMethod.GET)
    public Result view(@PathVariable Integer id) {
        SpotCheck spotCheck = spotCheckService.get(id);
        List<SpotCheckItem> itemList = spotCheckItemService.findByParentId(id);
        spotCheck.setItemList(itemList);
        return ResultGenerator.success(spotCheck);
    }

    @ApiOperation(value = "点检类型")
    @GetMapping(value="/type")
    public @ResponseBody
    Result type() {

        List<String> spotCheckTypes = dictionaryItemService.findValueByThemeValueAndEnable("点检类型",true);
        if(spotCheckTypes != null && spotCheckTypes.size() > 0) {
            return ResultGenerator.success(spotCheckTypes);
        }

        return ResultGenerator.success();
    }
}
