package com.nantian.cloud.dbcapp.carbon.contorller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.nantian.cloud.dbcapp.carbon.domain.CarbonPage;
import com.nantian.cloud.dbcapp.carbon.service.*;
import com.nantian.sc.cloud.common.core.util.R;
import com.nantian.sc.cloud.common.security.service.OAuthTokenUser;
import com.nantian.sc.cloud.common.security.service.ScUser;
import com.nantian.sc.cloud.common.security.util.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import com.nantian.cloud.dbcapp.carbon.domain.ent.*;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 计量器具信息 前端控制器
 * </p>
 *
 * @author wujing
 * @since 2022-09-28
 */
@Slf4j
@CrossOrigin
@RestController
@Api(tags = "企业-计量器具")
@RequestMapping("/enterprise/instrument")
public class InstrumentInfoController {

    @Autowired
    private InstrumentInfoService service;

    @Autowired
    private InstrumentEquipmentService instrumentEquipmentService;

    @Autowired
    private InstrumentLevelService instrumentLevelService;

    @Autowired
    private InstrumentCategoryService instrumentCategoryService;

    @Autowired
    private InstrumentVerifyInfoService instrumentVerifyInfoService;




    @ApiOperation("查询列表")
    @PostMapping("/list")
    public R list(@ApiParam(name = "page", value = "") @RequestBody InstrumentInfo entity,
                  @RequestParam(defaultValue = "1") int pageNum,
                  @RequestParam(defaultValue = "10") int pageSize) {
        List<InstrumentLevel> instrumentLevelList = instrumentLevelService.selectList();
        List<InstrumentCategory> instrumentCategoryList = instrumentCategoryService.selectList();
        Page param = new Page(pageNum, pageSize);
        IPage<InstrumentInfo> instrumentInfoList = service.getList(param,entity);
        if (!instrumentInfoList.getRecords().isEmpty()){
            String entId = instrumentEquipmentService.getEntId(entity.getEntCode());
            Map<Long, String> levelMap = instrumentLevelList.stream().collect(Collectors.toMap(InstrumentLevel::getLevelCode, InstrumentLevel::getLevelName));
            Map<Long, String> categoryMap = instrumentCategoryList.stream().collect(Collectors.toMap(InstrumentCategory::getCategoryCode, InstrumentCategory::getCategoryName));
            for (InstrumentInfo i : instrumentInfoList.getRecords()) {
                if (i.getLevel() != null) {
                    i.setLevelName(levelMap.get(i.getLevel()));
                }

                if (i.getCategory() != null) {
                    i.setCategoryName(categoryMap.get(i.getCategory()));
                }

                if (i.getStatus() != null && i.getStatus() == 1) {
                    i.setStatusName("启用");
                }

                if (i.getStatus() != null && i.getStatus() == 0) {
                    i.setStatusName("停用");
                }
            }
            //处理检定日期
            List<Integer> ids = instrumentInfoList.getRecords().stream().map(InstrumentInfo::getId).collect(Collectors.toList());
            for (InstrumentInfo instrumentInfo : instrumentInfoList.getRecords()) {
                InstrumentVerifyInfo instrumentVerifyInfo = instrumentVerifyInfoService.list(new LambdaQueryWrapper<InstrumentVerifyInfo>()
                        .eq(InstrumentVerifyInfo::getEntId, entId)
                        .eq(InstrumentVerifyInfo::getInstrumentId, instrumentInfo.getId())
                        .orderByDesc(InstrumentVerifyInfo::getUpdateDate)).stream().findFirst().orElse(null);
                if (instrumentVerifyInfo != null) {
                    instrumentInfo.setVerifyUnit(instrumentVerifyInfo.getVerifyUnit());
                    instrumentInfo.setVerifyDate(instrumentVerifyInfo.getVerifyDate());
                    instrumentInfo.setValidateDate(instrumentVerifyInfo.getValidateDate());

                }
            }
        }
        return R.ok(instrumentInfoList);
    }


    @ApiOperation("查询列表(全部)")
    @PostMapping("/listAll")
    public R list(@ApiParam(name = "page", value = "") @RequestBody InstrumentInfo entity) {
        List list = service.listAll(entity);
        return R.ok(list);
    }


    @ApiOperation("查询")
    @PostMapping("/get")
    public R get(@ApiParam(name = "InstrumentInfo", value = "数据实体") @RequestBody InstrumentInfo entity) {
        Integer id = entity.getId();
        if (id == null) {
            return R.failed("id不能为空");
        }
        if (entity.getEntCode() == null) {
            return R.failed("企业信用代码不能为空");
        }

        return R.ok(service.selectById(entity.getEntCode(), id));
    }


    @ApiOperation("保存")
    @PostMapping("/save")
    public R save(@ApiParam(name = "InstrumentInfo", value = "计量器具档案") @RequestBody InstrumentInfo entity) {
        Integer id = entity.getId();
        InstrumentInfo instrumentInfo = null;
        if (entity.getEntCode() == null){
            return R.failed("企业信息不能为空");
        }
        String entId = instrumentEquipmentService.getEntId(entity.getEntCode());
        if (entId == null){
            return R.failed("企业信息不能为空");
        }
        if (id != null){
            instrumentInfo = service.selectById(entity.getEntCode(), id);
        }
        if (instrumentInfo != null) {
            return R.failed("该计量器具已存在，不允许重复填报");
        } else {
            entity.setEntId(entId);
            service.saveInfo(entity);
            return R.ok(entity);
        }
    }



    @ApiOperation("编辑")
    @PostMapping("/update")
    public R update(@ApiParam(name = "InstrumentInfo", value = "计量器具档案") @RequestBody InstrumentInfo entity) {
//        entity.setEntId();
        int flag = service.updateInfoById(entity);
        if (flag > 0) {
            return R.ok(entity);
        } else {
            return R.failed("修改失败");
        }
    }

    @ApiOperation("删除")
    @PostMapping("/delete")
    public R delete(@ApiParam(name = "InstrumentInfo", value = "数据实体") @RequestBody InstrumentInfo entity) {
        Integer id = entity.getId();
        if (id == null) {
            return R.failed("该计量器具不存在");
        }
        if (null == entity) {
            return R.failed("该计量器具不存在");
        }
        service.removeById(id);
        return R.ok("删除成功");
    }

    @ApiOperation("计量器具层级")
    @GetMapping("/getInstrumentLevel")
    public R getInstrumentLevel() {
        return R.ok(instrumentLevelService.selectList());
    }


    @ApiOperation("计量器具类别")
    @GetMapping("/getInstrumentCode")
    public R getInstrumentCode() {
        return R.ok(instrumentCategoryService.selectList());
    }

    @ApiOperation("计量器具配备")
    @PostMapping("/saveEquipment")
    public R saveEquipment(@ApiParam(name = "InstrumentEquipment", value = "计量器具配备") @RequestBody InstrumentEquipment entity,@RequestParam String entCode) {
        InstrumentEquipment instrumentEquipment = instrumentEquipmentService.findByCategoryCode(entity.getCategoryCode(), entCode);
        if (instrumentEquipment != null) {
            return R.failed("该计量类别已存在，不允许重复填报");
        } else {
            entity.setEntId(instrumentEquipmentService.getEntId(entCode));
            instrumentEquipmentService.save(entity);
            return R.ok(entity);
        }
    }

    @ApiOperation("获取计量器具配备列表")
    @PostMapping("/getEquipmentList")
    public R getEquipmentList(@RequestParam String entCode,
                              @RequestParam(defaultValue = "1") int page,
                              @RequestParam(defaultValue = "10") int pageSize)  {
        Page param = new Page(page, pageSize);
        IPage<InstrumentEquipment> list = instrumentEquipmentService.getList(param,entCode);

        Map<Long, String> categoryMap = instrumentCategoryService.selectList().stream().collect(Collectors.toMap(InstrumentCategory::getCategoryCode, InstrumentCategory::getCategoryName));
        for (InstrumentEquipment i : list.getRecords()) {
            if (i.getCategoryCode() != null) {
                i.setCategoryName(categoryMap.get(i.getCategoryCode()));
            }
        }
        return R.ok(list);
    }

    @ApiOperation("修改计量器具配备情况")
    @PostMapping("/updateEquipment")
    public R updateEquipment(@ApiParam(name = "InstrumentEquipment", value = "计量器具配备") @RequestBody InstrumentEquipment entity) {
//        String entId = CurrentUserUtils.getCurEntId();
//        entity.setEntId(entId);
//        从token中获取
        int i = instrumentEquipmentService.updateByInsId(entity);
        if (i > 0) {
            return R.ok("修改成功");
        } else {
            return R.failed("修改失败");
        }

    }

    @ApiOperation("删除计量器具配备")
    @PostMapping("/deleteEquipment")
    public R deleteEquipment(@RequestParam String id,@RequestParam String entId) {
        int i = instrumentEquipmentService.deleteByInsId(id, entId);
        if (i > 0) {
            return R.ok("删除成功");
        } else {
            return R.failed("删除失败");
        }
    }

    //改企业有的计量器具
    @ApiOperation("获得企业已装配的计量器具列表")
    @PostMapping("/getUseEquipment")
    public R getCatFromEnt(@RequestParam String entCode)  {
        List<InstrumentInfo> instrumentInfos = service.selectByEntId(entCode);
        Set<Long> uniqueCategcodes = instrumentInfos.stream()
                .map(InstrumentInfo::getCategory) // 提取categcode字段
                .collect(Collectors.toSet());
        List<InstrumentCategory> instrumentCategoryList = instrumentCategoryService.listByIds(uniqueCategcodes)
                .stream().collect(Collectors.toList());
        return R.ok(instrumentCategoryList);
    }

}

