package com.winsun.controller;

import com.baomidou.mybatisplus.enums.SqlLike;
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.auth.core.util.DateUtil;
import com.winsun.auth.core.util.IOUtils;
import com.winsun.bean.*;
import com.winsun.mapper.*;
import com.winsun.utils.ExcelDealUtils;
import com.winsun.utils.MyBatisPlusUpdateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 院线通订单管理
 *
 * @Author: xiangli
 * @Date:
 */
@Slf4j
@RestController
@RequestMapping("/yxtOrder")
public class YxtOrderController extends BaseController {
    /**
     * 导入
     */
    private static final int HEADER_NUM = -1;
    private static final int SHEET_INDEX = 0;
    /**
     * KPI信息模板列名
     */
    private static String SL_reportDaily = "汇总任务量";
    private static String SL_collectiveSales = "参与集中营销";
    private static String SL_weeklyMeeting = "组织周例会";
    private static String SL_organTraining = "定制扫楼营销方案";
    private static String SL_designPlan = "组织培训";
    private static String SL_kpi = "KPI总值";
    private static String SL_month = "KPI月份";
    private static String SL_sysuName = "姓名(必填)";
    private static String SL_account = "账号(必填)";
    private static String SL_substName = "县分";
    private static String SL_schoolName = "学校";

    @Autowired
    private YxtOrderMapper yxtOrderMapper;
    @Autowired
    private YxtCouponMapper yxtCouponMapper;
    @Autowired
    private YxtOrderDetailMapper yxtOrderDetailMapper;
    @Autowired
    private SchoolMapper schoolMapper;
    @Autowired
    private UserSchoolMapper userSchoolMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    @Qualifier("redisStringTemplate")
    private RedisTemplate redisTemplate;

    /**
     * 取消院线通订单
     *
     * @param id 需要取消的id
     * @return
     */
    @Permission(menuname = "取消院线通订单", value = "delete", method = RequestMethod.POST)
    public ResponseData<String> deleteProduct(@RequestParam(name = "id", required = false) String id) {
        ShiroUser user = getShiroUser();
        if (!user.getRoleNames().stream().anyMatch(roleName -> StringUtils.equalsAny(roleName, "超级管理员"))) {
            return ResponseData.error("无数据权限");
        }
        if (StringUtils.isNotBlank(id)) {
            Wrapper wrapper = new EntityWrapper<>();
            wrapper.eq(StringUtils.isNotBlank(id),"id", id);
            Map<String, Object> dataMapping = new HashMap<>();
            dataMapping.put("state", 4);//已取消订单
            yxtOrderMapper.updateForSet(MyBatisPlusUpdateUtils.toUpdateSet(dataMapping), wrapper);
            List<Integer> yxtIds = new ArrayList<>();
            Wrapper<YxtOrderDetail> wrapper0 = new EntityWrapper<>();
            wrapper0.eq("order_id", id);
            List<YxtOrderDetail> yxtOrderList = yxtOrderDetailMapper.selectList(wrapper0);
            for (YxtOrderDetail yod : yxtOrderList) {
                Wrapper wrapper11 = new EntityWrapper<>();
                wrapper11.eq("id", yod.getYxtId());
                Map<String, Object> dataMapping11 = new HashMap<>();
                dataMapping11.put("state", 1);
                yxtCouponMapper.updateForSet(MyBatisPlusUpdateUtils.toUpdateSet(dataMapping11), wrapper11);
            }
            return ResponseData.success("操作成功！");
        }
        return ResponseData.error("删除id不通为空!");
    }

    /**
     * @param orderId
     * @return
     */
    @Permission(menuname = "通过ID获取院线通券信息", value = "getYxtCard", method = RequestMethod.POST)
    public ResponseData<Page<YxtCoupon>> getYxtCard(
            @RequestParam(name = "orderId", required = false) String orderId,
            @RequestParam(name = "pageNo") int pageNo, @RequestParam(name = "pageSize") int pageSize) {

        Page<YxtCoupon> page = new Page<>(pageNo, pageSize);
        List<YxtCoupon> dataList = new ArrayList<>();
        List<Integer> yxtIds = new ArrayList<>();
        Wrapper<YxtOrderDetail> wrapper = new EntityWrapper<>();
        wrapper.eq("order_id", orderId);
        List<YxtOrderDetail> yxtOrderList = yxtOrderDetailMapper.selectList(wrapper);
        for (YxtOrderDetail yxtOrderDetail : yxtOrderList) {
            yxtIds.add(yxtOrderDetail.getYxtId());
        }
        Wrapper<YxtCoupon> yxtCouponWrapper = new EntityWrapper<>();
        yxtCouponWrapper.in("id",yxtIds);
        List<YxtCoupon> couponList = yxtCouponMapper.selectList(yxtCouponWrapper);
        if (couponList.size() < pageSize) {
            dataList = couponList;
        } else {
            dataList = couponList.subList((pageNo - 1) * pageSize, pageNo * pageSize);
        }

        page.setRecords(dataList);
        page.setTotal(couponList.size());
        return ResponseData.success(page);
    }

    /**
     * @param name
     * @param account
     * @param substName
     * @param schoolName
     * @param month
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Permission(menuname = "查询院线通订单信息", value = "list", method = RequestMethod.POST)
    public ResponseData<Page<Map<String, Object>>> listProduct(
            @RequestParam(name = "name", required = false) String name,
            @RequestParam(name = "account", required = false) String account,
            @RequestParam(name = "state", required = false) String state,
            @RequestParam(name = "substName", required = false) String substName,
            @RequestParam(name = "schoolName", required = false) String schoolName,
            @RequestParam(name = "month", required = false) String month,
            @RequestParam(name = "orderNum", required = false) String orderNum,
            @RequestParam(name = "pageNo") int pageNo, @RequestParam(name = "pageSize") int pageSize) {
        ShiroUser user = getShiroUser();

        String month1 = "";
        String month2 = "";
        if (StringUtils.isNotBlank(month)) {
            String[] months = month.split("\\,");
            if (!month.equals(",") && StringUtils.isNotEmpty(month)) {
                month1 = months[0];
                month2 = months[1];
            }
        }
        Page<Map<String, Object>> page = new Page<>(pageNo, pageSize);
        List<Map<String, Object>> dataList = new ArrayList<>();
        List<Map<String, Object>> list = new ArrayList<>();

        Wrapper<YxtOrder> wrapper = new EntityWrapper();
        wrapper.eq(StringUtils.isNotBlank(orderNum), "order_num", orderNum);
        wrapper.eq(StringUtils.isNotBlank(state), "state", state);
        if(StringUtils.isNotBlank(month1) && StringUtils.isNotBlank(month2)){
            wrapper.between("update_date",month1,month2);
        }
        List<YxtOrder> yxtOrders = yxtOrderMapper.selectList(wrapper);
        List<String> userIds = new ArrayList<>();
        for (YxtOrder order : yxtOrders) {
            userIds.add(order.getUserId());
        }

        Wrapper<SysUser> sysWrapper = new EntityWrapper<>();
        sysWrapper.like(StringUtils.isNotBlank(name), "name", name, SqlLike.DEFAULT);
        sysWrapper.like(StringUtils.isNotBlank(account), "account", account, SqlLike.DEFAULT);
        sysWrapper.in("id", userIds);
        List<SysUser> sysUserList = sysUserMapper.selectList(sysWrapper);
        List<String> userIds0 = new ArrayList<>();
        for (SysUser sysUser : sysUserList) {
            userIds0.add(sysUser.getId());
        }
        if (sysUserList.size() == 0) {
            page.setRecords(null);
            page.setTotal(0);
            return ResponseData.success(page, "查询成功！");
        }
        Wrapper<UserSchool> usWrapper = new EntityWrapper<>();
        usWrapper.in("user_id", userIds0);
        List<UserSchool> userSchoolList = userSchoolMapper.selectList(usWrapper);
        List<String> userIds1 = new ArrayList<>();
        List<String> schoolIds = new ArrayList<>();
        for (UserSchool userSchool : userSchoolList) {
            userIds1.add(userSchool.getUserId());
            schoolIds.add(userSchool.getSchoolId());
        }

        Wrapper<School> schoolWrapper = new EntityWrapper<>();
        schoolWrapper.eq(StringUtils.isNotBlank(substName), "sub_name", substName);
        schoolWrapper.eq(StringUtils.isNotBlank(schoolName), "school_name", schoolName);
        schoolWrapper.in("id", schoolIds);
        List<School> schoolList = schoolMapper.selectList(schoolWrapper);
        if (schoolList.size() == 0) {
            page.setRecords(null);
            page.setTotal(0);
            return ResponseData.success(page, "查询成功！");
        }
        for (YxtOrder order : yxtOrders) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", order.getId());
            map.put("orderNum", order.getOrderNum());
            map.put("totalPrice", order.getTotalPrice());
            map.put("state", order.getState());
            map.put("updateDate", order.getUpdateDate());
            map.put("delFlag", order.getDelFlag());
            map.put("goodsNum", order.getGoodsNum());
            map.put("unitPrice", order.getUnitPrice());
            map.put("orderType", order.getOrderType());
            for (SysUser sysUser : sysUserList) {
                if (order.getUserId().equals(sysUser.getId())) {
                    map.put("sysuName", sysUser.getName());
                    map.put("account", sysUser.getAccount());
                    break;
                }
            }
            for (UserSchool userSchool : userSchoolList) {
                if (order.getUserId().equals(userSchool.getUserId())) {
                    String schoolId = userSchool.getSchoolId();
                    for (School school : schoolList) {
                        if (schoolId.equals(school.getId() + "")) {
                            map.put("schoolName", school.getSchoolName());
                            map.put("substName", school.getSubName());
                            break;
                        }
                    }
                }
            }
            if(map.containsKey("account") && map.containsKey("schoolName")){
                list.add(map);
            }
        }

        if (yxtOrders.size() < pageSize) {
            dataList = list;
        } else {
            Integer endpageSize = (pageNo-1) == yxtOrders.size()/10?(pageNo-1)*pageSize+yxtOrders.size()%10:pageNo*pageSize;
            dataList = list.subList((pageNo-1)*pageSize, endpageSize);
        }

        page.setRecords(dataList);
        page.setTotal(yxtOrders.size());
        return ResponseData.success(page, "查询成功！");
    }

    /**
     * @param name
     * @param account
     * @param substName
     * @param schoolName
     * @param month
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Permission(menuname = "导出院线通订单信息", value = "excelOut", method = RequestMethod.POST)
    public void excelOut(
            @RequestParam(name = "name", required = false) String name,
            @RequestParam(name = "account", required = false) String account,
            @RequestParam(name = "state", required = false) String state,
            @RequestParam(name = "substName", required = false) String substName,
            @RequestParam(name = "schoolName", required = false) String schoolName,
            @RequestParam(name = "month", required = false) String month,
            @RequestParam(name = "orderNum", required = false) String orderNum,
            @RequestParam(name = "pageNo") int pageNo, @RequestParam(name = "pageSize") int pageSize) {
        ShiroUser user = getShiroUser();
        if (!user.getRoleNames().stream().anyMatch(roleName -> StringUtils.equalsAny(roleName, "超级管理员"))) {
            log.error("无数据权限");
        }
        String month1 = "";
        String month2 = "";
        if (StringUtils.isNotBlank(month)) {
            String[] months = month.split("\\,");
            if (!month.equals(",") && StringUtils.isNotEmpty(month)) {
                month1 = months[0];
                month2 = months[1];
            }
        }
        Page<Map<String, Object>> page = new Page<>(pageNo, pageSize);
        List<Map<String, Object>> dataList = new ArrayList<>();
        List<Map<String, Object>> list = new ArrayList<>();

        Wrapper<YxtOrder> wrapper = new EntityWrapper();
        wrapper.eq(StringUtils.isNotBlank(orderNum), "order_num", orderNum);
        wrapper.eq(StringUtils.isNotBlank(state), "state", state);
        if(StringUtils.isNotBlank(month1) && StringUtils.isNotBlank(month2)){
            wrapper.between("update_date",month1,month2);
        }
        List<YxtOrder> yxtOrders = yxtOrderMapper.selectList(wrapper);
        List<String> userIds = new ArrayList<>();
        for (YxtOrder order : yxtOrders) {
            userIds.add(order.getUserId());
        }

        Wrapper<SysUser> sysWrapper = new EntityWrapper<>();
        sysWrapper.like(StringUtils.isNotBlank(name), "name", name, SqlLike.DEFAULT);
        sysWrapper.like(StringUtils.isNotBlank(account), "account", account, SqlLike.DEFAULT);
        sysWrapper.in("id", userIds);
        List<SysUser> sysUserList = sysUserMapper.selectList(sysWrapper);
        List<String> userIds0 = new ArrayList<>();
        for (SysUser sysUser : sysUserList) {
            userIds0.add(sysUser.getId());
        }
        if (sysUserList.size() == 0) {
            log.info("查询SysUser表数据为空！");
        }
        Wrapper<UserSchool> usWrapper = new EntityWrapper<>();
        usWrapper.in("user_id", userIds0);
        List<UserSchool> userSchoolList = userSchoolMapper.selectList(usWrapper);
        List<String> userIds1 = new ArrayList<>();
        List<String> schoolIds = new ArrayList<>();
        for (UserSchool userSchool : userSchoolList) {
            userIds1.add(userSchool.getUserId());
            schoolIds.add(userSchool.getSchoolId());
        }

        Wrapper<School> schoolWrapper = new EntityWrapper<>();
        schoolWrapper.eq(StringUtils.isNotBlank(substName), "sub_name", substName);
        schoolWrapper.eq(StringUtils.isNotBlank(schoolName), "school_name", schoolName);
        schoolWrapper.in("id", schoolIds);
        List<School> schoolList = schoolMapper.selectList(schoolWrapper);
        if (schoolList.size() == 0) {
            log.info("查询School表数据为空！");
        }
        for (YxtOrder order : yxtOrders) {
            Map<String, Object> map = new HashMap<>();
            map.put("orderNum", order.getOrderNum());
            map.put("totalPrice", order.getTotalPrice());
            Integer state0 = order.getState();
            if(state0 == 1){
                map.put("state", "未付款");
            }else if(state0 == 2){
                map.put("state", "付款成功");
            }else if(state0 == 3){
                map.put("state", "付款失败");
            }else if(state0 == 4){
                map.put("state", "已取消订单");
            }
            map.put("orderType", order.getOrderType());
            for (SysUser sysUser : sysUserList) {
                if (order.getUserId().equals(sysUser.getId())) {
                    map.put("account", sysUser.getAccount());
                    map.put("sysuName", sysUser.getName());
                    break;
                }
            }
            for (UserSchool userSchool : userSchoolList) {
                if (order.getUserId().equals(userSchool.getUserId())) {
                    String schoolId = userSchool.getSchoolId();
                    for (School school : schoolList) {
                        if (schoolId.equals(school.getId() + "")) {
                            map.put("schoolName", school.getSchoolName());
                            map.put("substName", school.getSubName());
                            break;
                        }
                    }
                }
            }
            map.put("updateDate", DateUtil.formatDate(order.getUpdateDate(),"yyyy-mm-dd"));
            if(map.containsKey("account") && map.containsKey("schoolName")){
                list.add(map);
            }
        }
        ServletOutputStream os = null;
        XSSFWorkbook workbook = ExcelDealUtils.getWorkBook(ExcelDealUtils.yxtOrderExcel("院线通订单清单"), list);
        try {
            HttpServletResponse response = getHttpServletResponse();
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream");
            os = response.getOutputStream();
            workbook.write(os);
            os.flush();
        } catch (Exception e) {
            log.error("文件出错！" + e.getMessage(), e);
        } finally {
            IOUtils.closeQuite(workbook, os);
        }
    }

}
