package com.lz.modules.equipment.controller;


import com.lz.common.utils.PageUtils;
import com.lz.common.utils.R;
import com.lz.common.utils.StringUtil;
import com.lz.modules.app.dao.DepartmentsDao;
import com.lz.modules.app.dto.GraphicsDto;
import com.lz.modules.app.dto.GraphicsStatisticalDto;
import com.lz.modules.app.entity.DepartmentsEntity;
import com.lz.modules.app.service.DepartmentsService;
import com.lz.modules.equipment.entity.OneCode;
import com.lz.modules.equipment.entity.OneCodeReq;
import com.lz.modules.equipment.entity.TCount;
import com.lz.modules.equipment.service.IEquipmentInfoService;
import com.lz.modules.equipment.service.OneCodeService;
import com.lz.modules.equipment.service.TCountService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/oneCode")
public class OneCodeController {


    @Autowired
    private OneCodeService oneCodeService;

    @Autowired
    private IEquipmentInfoService equipmentInfoService;

    @Autowired
    private DepartmentsDao departmentsDao;

    @Autowired
    private DepartmentsService departmentsService;

    @Autowired
    private TCountService tCountService;


    /**
     * 获取code编码，
     */
    @RequestMapping("/get/getPrints")
    @RequiresPermissions("user:device:code:list")
    public R getPrints(@RequestBody OneCodeReq req) {

        PageUtils pageUtils = oneCodeService.selectByReq(req);

        return R.ok().put("codes", pageUtils);
    }

    /**
     * 批量生成指定数量编码，
     */
    @RequestMapping("/new/prints")
    @RequiresPermissions("user:device:code:save")
    public R prints(@RequestParam int counts) {

        List<String> codes = new ArrayList<>();
        for (int i = 0; i < counts; i++) {
            String code = "LZ" + StringUtil.getRandomNum(8);
            codes.add(code);
        }
        oneCodeService.insertOneCodes(codes);
        return R.ok();
    }

    /**
     * 重打印一个编码，该编码已经在数据库中存在
     */
    @RequestMapping("/re/print")
    @RequiresPermissions("user:device:code:update")
    public R prints(@RequestParam String code) {
        OneCode oneCode = oneCodeService.selectByCode(code);
        if (oneCode != null) {
            oneCode.setIsPrint(0);
            oneCodeService.updateCoverOneCodeById(oneCode);
            return R.ok();
        } else {
            return R.error("条码不存在");
        }


    }

    /**
     * 获取未打印的编码，最多返回50个
     */
    @RequestMapping("/no/prints")
    public R prints() {
        List<String> codes = oneCodeService.selectNoPrints();
        return R.ok().put("data", codes);
    }

    /**
     * 更新打印过的编码
     */
    @RequestMapping("/update/prints")
    public R updatePrints(@RequestBody List<String> codes) {
        //List<String> codes = oneCodeService.selectNoPrints();
        oneCodeService.updatePrintOneCodes(codes);
        return R.ok();
    }

    @RequestMapping("/get/nums")
    public R getNums( ) {
        List<TCount> tCounts = tCountService.selectListLimit(10);
        for(TCount tCount:tCounts){
            tCount.setName( "第 " + tCount.getNum()+ " 次");
        }
        return R.ok().put("numbers",tCounts);
    }

    /**
     * 更新打印过的编码
     */
    @RequestMapping("/get/resourceItuation/{id}")
    public R resourceItuation(@PathVariable("id") Integer id) {
        TCount count = new TCount();
        count.setNum(id);
        if (id == null || id <= 0) {
            count = tCountService.selectMaxTCount();
        }
        Map data = new HashMap();
        List<GraphicsStatisticalDto> genderRows = new ArrayList<>();
        int countAll = equipmentInfoService.selectCountAllByState(count.getNum());
        int badDevNum = equipmentInfoService.selectCountByState(count.getNum(), 2);
        int shiftDevNum = equipmentInfoService.selectCountByState(count.getNum(), 3);
        int sellDevNum = equipmentInfoService.selectCountByState(count.getNum(), 1);
        int notfindDevNum = equipmentInfoService.selectCountByNotFind(count.getNum());

        GraphicsDto genderDistribution = new GraphicsDto();
        GraphicsStatisticalDto d1 = new GraphicsStatisticalDto();//故障设备
        d1.setCategory("故障设备");
        d1.setNumber(badDevNum);
        double rate1 = getRate(badDevNum,countAll);
        d1.setRate(rate1 + "%");
        genderRows.add(d1);

        GraphicsStatisticalDto d2 = new GraphicsStatisticalDto();//调拨设备
        d2.setCategory("调拨设备");
        d2.setNumber(shiftDevNum);
        double rate2 = getRate(shiftDevNum,countAll);
        d2.setRate(rate2 + "%");
        genderRows.add(d2);

        GraphicsStatisticalDto d3 = new GraphicsStatisticalDto();//售出设备
        d3.setCategory("售出设备");
        d3.setNumber(sellDevNum);
        double rate3 = getRate(sellDevNum,countAll);
        d3.setRate(rate3 + "%");
        genderRows.add(d3);

        GraphicsStatisticalDto d4 = new GraphicsStatisticalDto();//未盘点资产
        d4.setCategory("未盘点资产");
        d4.setNumber(notfindDevNum);
        double rate4 = getRate(notfindDevNum,countAll);
        d4.setRate(rate4 + "%");
        genderRows.add(d4);

        GraphicsStatisticalDto d5 = new GraphicsStatisticalDto();//正常设备
        d5.setCategory("正常设备");
        int b = countAll - badDevNum - shiftDevNum - sellDevNum - notfindDevNum;
        d5.setNumber(b);
        double rate5 = 1 - rate1 - rate2 - rate3 - rate4;
        d5.setRate(rate5 + "%");
        genderRows.add(d5);


        genderDistribution.setRows(genderRows);
        data.put("genderDistribution", genderDistribution);

        List<GraphicsStatisticalDto> ageRows = new ArrayList<>();
        int countAllDepartment = equipmentInfoService.selectCountAllDepartment(count.getNum());
        List<DepartmentsEntity> departmentsEntities = departmentsDao.selectDeparmentLevel1();
        double sumRate = 0;
        int sumNum = 0;
        for (int i = 0; i < departmentsEntities.size(); i++) {
            DepartmentsEntity departmentsEntity = departmentsEntities.get(i);
            int renshiDevNum = equipmentInfoService.selectCountByDepartmentIds(count.getNum(),
                    departmentsService.selectAllChildDepartmentIds(departmentsEntity.getDepartmentId()));
            GraphicsStatisticalDto graphicsStatisticalDto = new GraphicsStatisticalDto();
            double rate =getRate(renshiDevNum,countAll);
            sumRate += rate;
            sumNum += renshiDevNum;
            graphicsStatisticalDto.setRate(rate + "%");
            graphicsStatisticalDto.setCategory(departmentsEntity.getDepartmentName());
            graphicsStatisticalDto.setNumber(renshiDevNum);
            ageRows.add(graphicsStatisticalDto);
        }

        GraphicsStatisticalDto graphicsStatisticalDto = new GraphicsStatisticalDto();
        double rate = 1 - sumRate;
        int renshiDevNum = countAllDepartment - sumNum;
        graphicsStatisticalDto.setCategory("其他");
        graphicsStatisticalDto.setRate(rate + "%");
        graphicsStatisticalDto.setNumber(renshiDevNum);
        ageRows.add(graphicsStatisticalDto);

        GraphicsDto ageDistribution = new GraphicsDto();
        ageDistribution.setRows(ageRows);
        data.put("ageDistribution", ageDistribution);

        R ret = R.ok();
        ret.put("data", data);
        return ret;
    }


    public double getRate(int a ,int b ){
        return new BigDecimal(a).divide(new BigDecimal(b),4,BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100))
                .setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    }
}
