package com.lz.modules.equipment.controller;

import com.lz.common.emun.EquipmentState;
import com.lz.common.utils.R;
import com.lz.common.utils.StringUtil;
import com.lz.modules.app.annotation.Login;
import com.lz.modules.app.entity.StaffEntity;
import com.lz.modules.app.service.StaffService;
import com.lz.modules.equipment.entity.*;
import com.lz.modules.equipment.entity.model.*;
import com.lz.modules.equipment.service.*;
import com.lz.modules.sys.controller.AbstractController;
import com.lz.modules.sys.entity.SysUserEntity;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Author: djc
 * @Desc:
 * @Date: 2020/7/24 16:19
 */
@Slf4j
@RestController
@RequestMapping("api")
public class EquipmentController extends AbstractController {

    @Autowired
    private IEquipmentInfoService iEquipmentInfoService;
    @Autowired
    private IEquipmentTypeService iEquipmentTypeService;
    @Autowired
    private EquipmentBrandService equipmentBrandService;
    @Autowired
    private EquipmentSpecsService equipmentSpecsService;
    @Autowired
    private IEquipmentFlowRecordService iEquipmentFlowRecordService;
    @Autowired
    private StaffService staffService;
    @Autowired
    private EquipmentQrService equipmentQrService;
    @Autowired
    private SpecialApplyInfoService specialApplyInfoService;

    @GetMapping("findEquipmentById")
    @RequiresPermissions("user:device:pandian")
    public R findEquipmentById(@Valid @RequestParam @NotNull(message = "设备标识不能为空") String code){
        EquipmentInfo equipmentInfo = iEquipmentInfoService.selectEquipmentInfoByCode(code);
        if(equipmentInfo==null){
            return R.ok();
        }
        FindEquipmentResModel model = new FindEquipmentResModel();
        /*//下面的逻辑有bug下周修复20200925 20200927修复，注释掉
        EquipmentType equipmentType = iEquipmentTypeService.selectByType(equipmentInfo.getType());
        EquipmentBrand equipmentBrand = equipmentBrandService.selectByBrand(equipmentInfo.getBrandName());
        EquipmentSpecs equipmentSpecs = equipmentSpecsService.selectSpecs(equipmentInfo.getSpecType());*/
        BeanUtils.copyProperties(equipmentInfo,model);
        model.setState(equipmentInfo.getEquipmentState());
        if(equipmentInfo.getSaiId()!=null){
            model.setUserId(equipmentInfo.getSaiId());
            model.setEmployee(false);
        }
        model.setTypeId(equipmentInfo.getTypeId());
        model.setBrandId(equipmentInfo.getBrandId());
        model.setSpecId(equipmentInfo.getSpecsId());
        /*Optional.ofNullable(equipmentType).ifPresent(equipmentType1 -> model.setTypeId(equipmentType1.getId()));
        Optional.ofNullable(equipmentBrand).ifPresent(equipmentBrand1 -> model.setBrandId(equipmentBrand1.getId()));
        Optional.ofNullable(equipmentSpecs).ifPresent(new Consumer<EquipmentSpecs>() {
            @Override
            public void accept(EquipmentSpecs equipmentSpecs1) {
                model.setSpecId(equipmentSpecs1.getId());
            }
        });*/
        addRecord(equipmentInfo);
        return R.ok().put("data", model);

    }


    /*@PostMapping("addEquipment")
    @ApiOperation(value = "录入设备信息",produces = MediaType.APPLICATION_JSON_VALUE)
    public Result addEquipment(@RequestBody @Valid AddEquipmentModel model){
        EquipmentInfo code = iEquipmentInfoService.selectEquipmentInfoByCode(model.getCode());
        if(code != null){
            log.info("设备存在，进行归还操作");
        }
        EquipmentInfo info = new EquipmentInfo();
        BeanUtils.copyProperties(model,info);
        int i = iEquipmentInfoService.addEquipment(info);
        if(i>0){
            return Result.ok();
        }
        return Result.error();

    }*/

    @PostMapping("changeEquipmentInfo")
    @RequiresPermissions("user:device:pandian")
    public R changeEquipmentState(@RequestBody @Valid ChangeEquipmentModel model){
        EquipmentDto dto = new EquipmentDto();
        BeanUtils.copyProperties(model,dto);
        try {
            iEquipmentInfoService.changeEquipmentInfo(dto,getUser());
        } catch (Exception e) {
            log.error("绑定设备异常{}",e);
            return R.error(e.getMessage());
        }
        return R.ok();

    }


    @GetMapping("findRrBySpec")
    @RequiresPermissions("user:device:pandian")
    public R getRrBySpec(@Valid @RequestParam @NotNull(message = "规格不能为空") Long specId){
        List<EquipmentQr> rrBySpec = equipmentQrService.findRrBySpec(specId);
        if(CollectionUtils.isEmpty(rrBySpec)){
            return R.ok();
        }
        List<FindRrBySpecResModel> data = rrBySpec.stream().map(new Function<EquipmentQr, FindRrBySpecResModel>() {
            @Override
            public FindRrBySpecResModel apply(EquipmentQr equipmentQr) {
                boolean employee = equipmentQr.getType()==1;
                FindRrBySpecResModel model = new FindRrBySpecResModel();
                BeanUtils.copyProperties(equipmentQr,model);
                model.setEmployee(employee);
                if(employee){
                    StaffEntity employeesInfo = staffService.selectStaffById(equipmentQr.getOwnerId());
                    if(employeesInfo!=null){
                        model.setName(employeesInfo.getName());
                    }
                }else {
                    SpecialApplyInfo specialApplyInfo = specialApplyInfoService.selectSpecialApplyInfoById(equipmentQr.getOwnerId());
                    if(specialApplyInfo!=null){
                        model.setName(specialApplyInfo.getTypeDesc());
                    }
                }

                return model;
            }
        }).collect(Collectors.toList());
        return R.ok().put("data", data);

    }


    @PostMapping("findEquipmentType")
    @RequiresPermissions("user:device:pandian")
    public R findEquipmentType(@RequestBody @ApiParam FindEquipmentTypeModel model){
        String[] split = null;
        int length = 0;
        List<FindEquipmentTypeResModel> data = new ArrayList<>();
        if(!StringUtil.isBlank(model.getCategorys())){
            split = model.getCategorys().split(",");
            length = split.length;
        }
        if(length==0){
            List<EquipmentType> list = iEquipmentTypeService.selectEquipmentTypeByType(model.getName());
            if(CollectionUtils.isEmpty(list)){
                return R.ok().put("data", data);
            }

            list.stream().forEach(equipmentType -> {
                FindEquipmentTypeResModel mod = new FindEquipmentTypeResModel();
                BeanUtils.copyProperties(equipmentType,mod);
                mod.setDesc(equipmentType.getType());
                data.add(mod);
            });
        }
        if(length==1){
            Long typeId = Long.valueOf(split[0]);
            List<EquipmentBrand> list = equipmentBrandService.selectEquipmentBrandByTypeAndLikeBrand(typeId, model.getName());
            if(CollectionUtils.isEmpty(list)){
                return R.ok().put("data", data);
            }
            list.stream().forEach(equipmentBrand -> {
                FindEquipmentTypeResModel mod = new FindEquipmentTypeResModel();
                BeanUtils.copyProperties(equipmentBrand,mod);
                mod.setDesc(equipmentBrand.getBrand());
                data.add(mod);
            });

        }
        if(length==2){
            Long typeId = Long.valueOf(split[0]);
            Long brandId = Long.valueOf(split[1]);
            List<EquipmentSpecs> list = equipmentSpecsService.selectEquipmentSpecsByTypeBrandLikeSpecss(typeId, brandId, model.getName());
            if(CollectionUtils.isEmpty(list)){
                return R.ok().put("data", data);
            }
            list.stream().forEach(equipmentSpecs -> {
                FindEquipmentTypeResModel mod = new FindEquipmentTypeResModel();
                BeanUtils.copyProperties(equipmentSpecs,mod);
                mod.setDesc(equipmentSpecs.getSpecs());
                data.add(mod);
            });
        }
        return R.ok().put("data", data);

    }

    @PostMapping("statisticalEquipment")
    public void statisticalEquipment(){
        //iEquipmentInfoService

    }


    private void addRecord(EquipmentInfo equipmentInfo){
        //记录盘点日志
        EquipmentFlowRecord record = new EquipmentFlowRecord();
        SysUserEntity user = getUser();
        BeanUtils.copyProperties(equipmentInfo,record);
        record.setRecordUserId(user.getUserId());
        record.setRecordUser(user.getRealName());
        record.setChangeType(EquipmentState.CHECK.getCode());
        record.setEquipmentId(equipmentInfo.getId());
        iEquipmentFlowRecordService.insertEquipmentFlowRecord(record);
    }

}
