package xiaoqu.home.open.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import xiaoqu.home.open.aop.AvoidRepeatSubmit;
import xiaoqu.home.open.controller.export.operation.ObjectOperationUnionOutput;
import xiaoqu.home.open.controller.export.operation.ObjectParentOperationUnionOutput;
import xiaoqu.home.open.controller.export.scenes.ObjectFlag;
import xiaoqu.home.open.controller.input.matter.MatterInsert;
import xiaoqu.home.open.controller.input.matter.MatterPageInput;
import xiaoqu.home.open.controller.input.matter.MatterUpdate;
import xiaoqu.home.open.controller.input.plan.WageInsert;
import xiaoqu.home.open.controller.input.plan.WagePageInput;
import xiaoqu.home.open.model.db1.District;
import xiaoqu.home.open.model.db1.User;
import xiaoqu.home.open.model.db2.*;
import xiaoqu.home.open.model.db2.Object;
import xiaoqu.home.open.publicBean.BaseOutput;
import xiaoqu.home.open.publicBean.PageOutput;
import xiaoqu.home.open.service.RedisService4;
import xiaoqu.home.open.service.db1.DistrictService;
import xiaoqu.home.open.service.db2.*;
import xiaoqu.home.open.task.bean.DeleteEntityNotice;
import xiaoqu.home.open.task.bean.NameModifyNotice;
import xiaoqu.home.open.utils.ResultResponseBeanUtil;
import xiaoqu.home.open.utils.UserUtils;
import xiaoqu.home.open.utils.WrapperUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.util.*;

/**
 *
 */
@Api(value = "时薪相关")
@Controller
@RequestMapping("/wage")
@Slf4j
public class WageController {
    @Autowired
    WageService wageService;
    @Autowired
    DistrictService districtService;
    @Autowired
    TaskDistrictParamService taskDistrictParamService;
    @Autowired
    private RedisService4 redisService4;

    @ApiOperation(value = "时薪分页查询")
    @ResponseBody
    @RequestMapping(value = "/wagePageList", method = RequestMethod.POST)
    public BaseOutput<PageOutput<Wage>> wagePageList(HttpServletRequest request, @RequestBody WagePageInput input) {
//        User user = UserUtils.getUser(request);
        if (input.getDistrictId() == null || input.getDistrictId() == 0) {
            return ResultResponseBeanUtil.fail("请选择站点");
        }
        log.info("【wagePageList】input" + JSONObject.toJSONString(input));
        QueryWrapper<Wage> wrapper = WrapperUtils.getWrapper(false);
        PageOutput<Wage> output = new PageOutput<Wage>();

        wrapper = WrapperUtils.beanToWrapper(wrapper, input);
        wrapper.orderByAsc("type");
        Page<Wage> pageList = new Page<Wage>(input.getPage(), input.getRows());
        List<Wage> wageList = wageService.page(pageList, wrapper).getRecords();

        output.setPage(pageList.getCurrent());
        output.setRecords(pageList.getTotal());
        output.setTotal(pageList.getPages());
        output.setRows(wageList);
        return ResultResponseBeanUtil.success(output);
    }

    @ApiOperation(value = "添加/修改事项信息")
    @ResponseBody
    @AvoidRepeatSubmit
    @RequestMapping(value = "/addOrUpdateWage", method = RequestMethod.POST)
    public BaseOutput<String> addOrUpdateWage(HttpServletRequest request, @RequestBody WageInsert input) {
        User user = UserUtils.getUser(request);
        if (input.getDistrictId() == null || input.getDistrictId() == 0) {
            return ResultResponseBeanUtil.fail("请选择站点");
        }
        if (input.getPoint() == null || input.getPoint() <= 0) {
            return ResultResponseBeanUtil.fail("请输入积分");
        }
        if (input.getAmount() == null || input.getAmount() <= 0) {
            return ResultResponseBeanUtil.fail("金额异常");
        }
        QueryWrapper<Wage> checkwrapper = WrapperUtils.getWrapper(false);
        checkwrapper.eq("type", input.getType());
        checkwrapper.eq("district_id", input.getDistrictId());
        checkwrapper.last("limit 1");
        Wage one = wageService.getOne(checkwrapper);
        District district = districtService.getById(input.getDistrictId());

        if(input.getId()!=null&&input.getId()>0){
            if(one!=null&&input.getId().longValue()!=one.getId().longValue()){
                return ResultResponseBeanUtil.fail("当前时薪类型已存在");
            }
            BeanUtils.copyProperties(input,one);
            setWage(input, user, one);
            wageService.updateById(one);
            return ResultResponseBeanUtil.success("修改成功");

        }else{
            if(one!=null){
                return ResultResponseBeanUtil.fail("当前时薪类型已存在");
            }
            Wage wage = new Wage();
            BeanUtils.copyProperties(input,wage);
            setWage(input, user, wage);
            wage.setDistrictId(district.getId());
            wage.setAgentId(district.getAgentId());
            wage.setPropertyId(district.getPropertyId());
            wage.setDistrictName(district.getDistrictName());
            wageService.save(wage);
            return ResultResponseBeanUtil.success("添加成功");

        }


    }

    private void setWage(WageInsert input, User user, Wage wage) {
        wage.setModifyId(user.getId());
        wage.setModifyName(user.getName());
        wage.setModifyTime(new Date());
        wage.setName(input.getName()+"("+ input.getAmount()+")");
        wage.setPoint(input.getPoint().doubleValue());
    }


    @ApiOperation(value = "根据积分获取对应时薪")
    @ResponseBody
    @RequestMapping(value = "/getAmount", method = RequestMethod.POST)
    public BaseOutput<Double> getAmount(HttpServletRequest request, @RequestBody WageInsert input) {
        User user = UserUtils.getUser(request);
        log.info("【getAmount】input" + JSONObject.toJSONString(input));


        QueryWrapper<TaskDistrictParam> wrapper = WrapperUtils.getWrapper(false);
        wrapper.eq("district_id", input.getDistrictId());
        wrapper.last(" limit 1");
        TaskDistrictParam one = taskDistrictParamService.getOne(wrapper);
        if(one==null){
            District district = districtService.getById(input.getDistrictId());

            TaskDistrictParam taskDistrictParam = new TaskDistrictParam();
            taskDistrictParam.setAgentId(district.getAgentId());
            taskDistrictParam.setPropertyId(district.getPropertyId());
            taskDistrictParam.setDistrictId(district.getId());
            taskDistrictParam.setDistrictName(district.getDistrictName());
            taskDistrictParam.setUserRestDuration(60);
            taskDistrictParam.setTaskNo(1L);
            taskDistrictParam.setCommonLimit(99);
            taskDistrictParam.setSpecialLimit(99);
            taskDistrictParam.setUrgentLimit(5);
            taskDistrictParam.setBeaconNo(1);
            taskDistrictParam.setPoint(1.0);
            taskDistrictParam.setWageBase(1.0);
            taskDistrictParamService.save(taskDistrictParam);
            redisService4.set("PoolOrderCount:1:"+district.getId().toString(),"5");
            redisService4.set("PoolOrderCount:2:"+district.getId().toString(),"99");
            redisService4.set("PoolOrderCount:3:"+district.getId().toString(),"99");
            return  ResultResponseBeanUtil.success(input.getPoint());

        }else {
            BigDecimal point = new BigDecimal(input.getPoint());
            BigDecimal amount = point.multiply(new BigDecimal(one.getWageBase())).divide(new BigDecimal(one.getPoint()),2,BigDecimal.ROUND_DOWN);
            double value = amount.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            return ResultResponseBeanUtil.success(value);

        }
    }


    @ApiOperation(value = "积分薪资配置分页查询")
    @ResponseBody
    @RequestMapping(value = "/wagePointPageList", method = RequestMethod.POST)
    public BaseOutput<PageOutput<TaskDistrictParam>> wagePointPageList(HttpServletRequest request, @RequestBody WagePageInput input) {
//        User user = UserUtils.getUser(request);
        if (input.getDistrictId() == null || input.getDistrictId() == 0) {
            return ResultResponseBeanUtil.fail("请选择站点");
        }
        log.info("【wagePointPageList】input" + JSONObject.toJSONString(input));
        QueryWrapper<TaskDistrictParam> wrapper = WrapperUtils.getWrapper(false);
        PageOutput<TaskDistrictParam> output = new PageOutput<TaskDistrictParam>();

        wrapper = WrapperUtils.beanToWrapper(wrapper, input);
//        wrapper.orderByAsc("order_by");
        Page<TaskDistrictParam> pageList = new Page<TaskDistrictParam>(input.getPage(), input.getRows());
        List<TaskDistrictParam> wageList = taskDistrictParamService.page(pageList, wrapper).getRecords();

        output.setPage(pageList.getCurrent());
        output.setRecords(pageList.getTotal());
        output.setTotal(pageList.getPages());
        output.setRows(wageList);
        return ResultResponseBeanUtil.success(output);
    }


    @ApiOperation(value = "设置积分薪资配置")
    @ResponseBody
    @AvoidRepeatSubmit
    @RequestMapping(value = "/setWagePoint", method = RequestMethod.POST)
    public BaseOutput<String> setWagePoint(HttpServletRequest request, @RequestBody WageInsert input) {
        User user = UserUtils.getUser(request);
        if (input.getDistrictId() == null || input.getDistrictId() == 0) {
            return ResultResponseBeanUtil.fail("请选择站点");
        }
        log.info("【setWagePoint】input" + JSONObject.toJSONString(input));
        TaskDistrictParam taskDistrictParam = taskDistrictParamService.getById(input.getId());
        if (taskDistrictParam == null ) {
            return ResultResponseBeanUtil.fail("数据异常");
        }
        taskDistrictParam.setWageBase(input.getWageBase());
        taskDistrictParam.setPoint(input.getPoint());
        taskDistrictParam.setMemo(input.getMemo());
        taskDistrictParam.setOpTime(new Date());
        taskDistrictParam.setOpUserId(user.getId());
        taskDistrictParam.setOpUserName(user.getName());
        try {
            taskDistrictParamService.updateById(taskDistrictParam);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultResponseBeanUtil.success("操作失败");
        }

        QueryWrapper<Wage> wrapper = WrapperUtils.getWrapper(false);
        wrapper.eq("district_id",taskDistrictParam.getDistrictId());
        List<Wage> list = wageService.list(wrapper);
        for (Wage wage:list             ) {
            BigDecimal point = new BigDecimal(wage.getPoint());
            BigDecimal amount = point.multiply(new BigDecimal(taskDistrictParam.getWageBase())).divide(new BigDecimal(taskDistrictParam.getPoint()),2,BigDecimal.ROUND_DOWN);
            double value = amount.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            wage.setAmount(value);
            wage.getName().substring(wage.getName().indexOf("("));
            wage.setName(wage.getName().replace(wage.getName().substring(wage.getName().indexOf("(")),"(")+wage.getAmount()+")");
            wageService.updateById(wage);
        }
        return ResultResponseBeanUtil.success("操作成功");
    }
}
