package com.winsun.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.winsun.auth.core.annotion.Permission;
import com.winsun.auth.core.base.controller.BaseController;
import com.winsun.auth.core.common.model.ResponseData;
import com.winsun.auth.core.shiro.ShiroUser;
import com.winsun.bean.HhrUser;
import com.winsun.bean.Order;
import com.winsun.bean.SalesList;
import com.winsun.mapper.*;
import com.winsun.service.IHhrUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

@Slf4j
@RestController
@RequestMapping("/hhrUser")
public class hhrUserController extends BaseController {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private AppMapper appMapper;

    @Autowired
    private SalesListMapper salesListMapper;

    @Autowired
    private HhrUserMapper hhrUserMapper;

    @Autowired
    private IHhrUserService hhrUserService;

    /**
     * 查询订单列表
     *
     * @param userId      用户id
     * @param pageNo      查询页码 默认首页
     * @param pageSize    查询每页数量 默认10
     * @param customer    查询条件-联系号码或联系人
     * @param orderStatus 查询条件-订单状态
     * @param userType    查询条件-用户类型
     * @param selectFlag  查询内容-0：个人   1：督导   默认0
     * @return
     */
    @ResponseBody
    @Permission(menuname = "督导查询", value = "getOrderList", method = RequestMethod.POST)
    public ResponseData<Map<String, Object>> getOrderList(String userId, Integer pageNo, Integer pageSize, String customer, String orderStatus, String userType, Integer selectFlag) {
        if (StringUtils.isBlank(userId)) {
            return ResponseData.error("userId为空");
        }
        Map<String, Object> resultMap = new HashMap<>();

        ShiroUser shiroUser = getShiroUser();
        HhrUser hhrUser = hhrUserMapper.selectById(shiroUser.getId());

        List<String> userList = new ArrayList<>();
        if (selectFlag == null || selectFlag == 0) {
            // 个人
            userList.add(userId);
        } else {
            // 成员订单
            if ("楼长".equals(hhrUser.getPosition())) {
                List<Integer> childrenUser = hhrUserService.getChildrenUser(shiroUser.getId());
                if (childrenUser.size() == 0) {
                    return ResponseData.error("当前账号无成员用户");
                }
                childrenUser.forEach(userid -> {
                    userList.add(userid + "");
                });
            }else if("总经理".equals(hhrUser.getPosition())){
                // 总经理
                List<String> managerSchoolList = appMapper.selectManagerSchool(userId);
                if (managerSchoolList == null || managerSchoolList.size() == 0) {
                    return ResponseData.error( "当前账号无负责的学校");
                }
                List<String> memberList = appMapper.selectUserBySchool(managerSchoolList);
                userList.addAll(memberList);
            }else{
                return ResponseData.error("无成员订单");
            }
        }

        Page<Order> page = new Page<>(pageNo == null ? 1 : pageNo, pageSize == null ? 10 : pageSize);
        Wrapper<Order> wrapper = new EntityWrapper<Order>();
        wrapper.in("hehuoren_id", userList);
        if (StringUtils.isNotBlank(customer)) {
            wrapper.addFilter("(contact_number LIKE '%" + customer + "%' OR customer_name LIKE '%" + customer + "%')");
        }
        wrapper.eq(StringUtils.isNotBlank(orderStatus), "order_status", orderStatus);
        wrapper.eq(StringUtils.isNotBlank(userType), "user_type", userType);
        wrapper.orderBy("create_time",false);

        List<Order> orderList = orderMapper.selectPage(page, wrapper);
        page.setRecords(orderList);
        resultMap.put("orderList", orderList);

        Wrapper<Order> numWrapper = wrapper.clone();
        numWrapper.setSqlSelect("COUNT(CASE WHEN order_status IN ('异常单','重新下单') THEN 1 END)AS errorNum," +
                "COUNT(CASE WHEN order_status IN ('审核中','待受理','待处理','待活体','待派奖','待选号','待配送','提交中') THEN 1 END)AS dealNum");
        numWrapper.eq(StringUtils.isNotBlank(orderStatus), "order_status", orderStatus);
        numWrapper.eq(StringUtils.isNotBlank(userType), "user_type", userType);
        List<Map<String, Object>> numList = orderMapper.selectMaps(numWrapper);
        resultMap.put("orderStatusNum", numList.get(0));

        return ResponseData.success(resultMap, "查询成功");
    }

    /**
     * 获取放号记录
     * @return
     */
    @Permission(menuname = "获取销售清单", value="getSallesList", method = RequestMethod.POST)
    public ResponseData<Page<SalesList>> getSalesList(Integer pageNo, Integer pageSize) {
        try{
            ShiroUser shiroUser = getShiroUser();
            if (shiroUser == null) {
                return ResponseData.error("请先登录");
            }

            Page<SalesList> page = new Page<>();
            page.setCurrent(pageNo);
            page.setSize(pageSize);

            Wrapper<SalesList> wrapper = new EntityWrapper<>();
            wrapper.eq("user_id", shiroUser.getId());
            wrapper.orderBy("create_time", false);
            List<SalesList> salesLists = salesListMapper.selectPage(page, wrapper);
            page.setRecords(salesLists);

            return ResponseData.success(page, "查询成功");
        }catch (Exception e){
            e.printStackTrace();
            return ResponseData.error("查询失败");
        }
    }

    /**
     * 更新销售县分
     * @param salesList
     * @return
     */
    @Permission(menuname = "更新销售县分", value = "updateSalesList", method = RequestMethod.POST)
    public ResponseData<String> updateSalesList(@RequestParam("id") Integer id,
                                                @RequestParam("salesSubst") String salesSubst,
                                                @RequestParam("salesSchool") String salesSchool) {

        try {
            ShiroUser shiroUser = getShiroUser();

            if (shiroUser == null) {
                return ResponseData.error("请先登录");
            }

            SalesList salesList = new SalesList();
            salesList.setId(id);
            salesList.setSalesSubst(salesSubst);
            salesList.setSalesSchool(salesSchool);
            salesListMapper.updateById(salesList);
            return ResponseData.success(null, "更新成功");
        }catch(Exception e) {
            e.printStackTrace();
            return ResponseData.error("更新失败");
        }

    }
}
