package cn.com.countrygarden.bi.main.controller.mediaResource;

import cn.com.countrygarden.bi.main.constant.mediaResource.MediaResourceConstant;
import cn.com.countrygarden.bi.main.core.Response;
import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.dao.mediaResource.BasicInfoMapper;
import cn.com.countrygarden.bi.main.dto.mediaResource.MediaOrderBillDto;
import cn.com.countrygarden.bi.main.dto.mediaResource.MediaOrderDto;
import cn.com.countrygarden.bi.main.dto.mediaResource.MediaOrderRunBillDto;
import cn.com.countrygarden.bi.main.exception.ServiceException;
import cn.com.countrygarden.bi.main.handler.mediaResource.MediaOrderExportHandle;
import cn.com.countrygarden.bi.main.service.mediaResource.MediaCommonService;
import cn.com.countrygarden.bi.main.service.mediaResource.MediaOrderRunService;
import cn.com.countrygarden.bi.main.service.mediaResource.MediaOrderService;
import cn.com.countrygarden.bi.main.service.twerp.hm.TbSysUserService;
import cn.com.countrygarden.bi.main.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

/**
 * <pre>
 *  订单管理
 * </pre>
 *
 * @author ferren  liao-r@neusoft.com
 * @version 1.00.00
 * <p>
 * <p>
 * <pre>
 * 修改记录
 *    修改后版本:     修改人：  修改日期:     修改内容:
 * </pre>
 */
@RestController
@RequestMapping("/api/media/order")
public class MediaOrderManageController {
    @Autowired
    private MediaOrderService mediaOrderService;
    @Autowired
    private MediaOrderRunService mediaOrderRunService;
    @Autowired
    private MediaOrderExportHandle mediaOrderExportHandle;
    @Autowired
    private MediaCommonService mediaCommonService;
    @Autowired
    private TbSysUserService tbSysUserService;
    @Autowired
    private BasicInfoMapper basicInfoMapper;

    /**
     * 查询订单
     *
     * @param dto
     * @return
     */
    @GetMapping("/pageList")
    public Result select(MediaOrderDto dto) {
        try {
            String orderStartDateStr = dto.getOrderStartDateStr();
            if (StringUtils.hasText(orderStartDateStr)) {
                dto.setOrderStartDate(DateUtil.parseDate(orderStartDateStr));
            }

            String orderEndDateStr = dto.getOrderEndDateStr();
            if (StringUtils.hasText(orderEndDateStr)) {
                dto.setOrderEndDate(DateUtil.parseDate(orderEndDateStr));
            }
            // 非总部设置权限
            boolean adminRole = mediaCommonService.isAdminRole();
            if (!adminRole) {
                Map<String, String> erpUserOrgan = basicInfoMapper.findErpUserOrgan(tbSysUserService.getCurrentSysUser().getUserCode());
                dto.setOrganCode(erpUserOrgan.get("organCode"));
            }// 有顺序关系
            // 执行状态
            if (MediaResourceConstant.ORDER_STATUS_TYPE.RUN.equals(dto.getOrderStatus())) {

                dto.setCurrentDate(new Date());
                //dto.setOrderEndDate(new Date());
            }
            // 已完成状态
            if (MediaResourceConstant.ORDER_STATUS_TYPE.DONE.equals(dto.getOrderStatus())) {
                Date date = DateUtil.parseDate(DateUtil.simpleFormat(new Date()));
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date);
                calendar.add(Calendar.DAY_OF_MONTH, 0);//+1今天的时间加一天
                Date time = calendar.getTime();
                dto.setOrderEndDate(time);
                dto.setOrderStatus(MediaResourceConstant.ORDER_STATUS_TYPE.RUN);
            }

            return Response.response(mediaOrderService.select(dto));
        } catch (ServiceException e) {
            return Response.responseFail(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Response.responseFail("查询订单异常！");
        }
    }

    /**
     * 查询订单明细
     *
     * @param param
     * @return
     */
    @GetMapping("/bill/pageList")
    public Result selectBill(MediaOrderBillDto param) {
        try {
            if (param.getOrderId() == null) {
                throw new ServiceException("订单id不能为空");
            }
            return Response.response(mediaOrderService.selectBillPageList(param));
        } catch (ServiceException e) {
            return Response.responseFail(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Response.responseFail("查询订单明细异常！");
        }
    }

    /**
     * 查询执行单
     *
     * @param param
     * @return
     */
    @GetMapping("/run/bill/pageList")
    public Result selectBill(MediaOrderRunBillDto param) {
        try {
            if (param.getOrderId() == null) {
                throw new ServiceException("订单id不能为空");
            }
            return Response.response(mediaOrderRunService.selectBillPageList(param));
        } catch (ServiceException e) {
            return Response.responseFail(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Response.responseFail("查询执行单异常！");
        }
    }

    /**
     * 锁定订单
     *
     * @param param
     * @return
     */
    @PostMapping("/lock")
    public Result lockBill(@RequestBody MediaOrderDto param) {
        try {
            if (param == null) {
                throw new ServiceException("参数不能为空");
            }
            if (param.getOrderStartDateStr() == null) {
                throw new ServiceException("开始时间不能为空");
            } else {
                param.setOrderStartDate(DateUtil.parseDate(param.getOrderStartDateStr()));
            }
            if (param.getOrderEndDateStr() == null) {
                throw new ServiceException("结束时间不能为空");
            } else {
                param.setOrderEndDate(DateUtil.parseDate(param.getOrderEndDateStr()));
            }
            return Response.response(mediaOrderService.lockBill(param));
        } catch (ServiceException e) {
            return Response.responseFail(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Response.responseFail("锁定订单异常！");
        }
    }

    /**
     * 执行订单
     *
     * @param param
     * @return
     */
    @PostMapping("/run")
    public Result runBill(@RequestBody MediaOrderDto param) {
        try {
            if (param == null) {
                throw new ServiceException("参数不能为空");
            }
            if (param.getOrderStartDateStr() == null) {
                throw new ServiceException("开始时间不能为空");
            } else {
                param.setOrderStartDate(DateUtil.parseDate(param.getOrderStartDateStr()));
            }
            if (param.getOrderEndDateStr() == null) {
                throw new ServiceException("结束时间不能为空");
            } else {
                param.setOrderEndDate(DateUtil.parseDate(param.getOrderEndDateStr()));
            }
            return Response.response(mediaOrderService.runBill(param));
        } catch (ServiceException e) {
            return Response.responseFail(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Response.responseFail("执行订单异常！");
        }
    }

    /**
     * 取消锁定
     *
     * @param param
     * @return
     */
    @PostMapping("/unlock")
    public Result unlockBill(@RequestBody MediaOrderDto param) {
        try {
            if (param == null) {
                throw new ServiceException("参数不能为空");
            }
            /*if (param.getOrderStartDateStr() == null) {
                throw new ServiceException("开始时间不能为空");
            } else {
                param.setOrderStartDate(DateUtil.parseDate(param.getOrderStartDateStr()));
            }
            if (param.getOrderEndDateStr() == null) {
                throw new ServiceException("结束时间不能为空");
            } else {
                param.setOrderEndDate(DateUtil.parseDate(param.getOrderEndDateStr()));
            }*/
            if (param.getOrderId() == null) {
                throw new ServiceException("orderId 参数不能为空");
            }
            return Response.response(mediaOrderService.unlockBill(param));
        } catch (ServiceException e) {
            return Response.responseFail(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Response.responseFail("取消锁定订单异常！");
        }
    }

    /**
     * 终止
     *
     * @param param
     * @return
     */
    @PostMapping("/final")
    public Result finalBill(@RequestBody MediaOrderDto param) {
        try {
            if (param == null) {
                throw new ServiceException("参数不能为空");
            }
            /*if (param.getOrderStartDateStr() == null) {
                throw new ServiceException("开始时间不能为空");
            } else {
                param.setOrderStartDate(DateUtil.parseDate(param.getOrderStartDateStr()));
            }*/
            if (param.getOrderFinalDateStr() == null) {
                throw new ServiceException("终止时间不能为空");
            } else {
                param.setFinalDate(DateUtil.parseDate(param.getOrderFinalDateStr()));
            }
            if (param.getOrderId() == null) {
                throw new ServiceException("orderId 参数不能为空");
            }
            return Response.response(mediaOrderService.finalBill(param));
        } catch (ServiceException e) {
            return Response.responseFail(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Response.responseFail("终止订单异常！");
        }
    }

    /**
     * 订单详情
     *
     * @param param
     * @return
     */
    /*@GetMapping("/detail")
    public void detail(MediaOrderDto param){
        mediaOrderService.orderDetail(param);
    }*/

    /**
     * 导出订单
     *
     * @param param
     * @return
     */
    @GetMapping("/export")
    public void export(MediaOrderDto param, HttpServletRequest request, HttpServletResponse response) {
        String orderStartDateStr = param.getOrderStartDateStr();
        if (StringUtils.hasText(orderStartDateStr)) {
            param.setOrderStartDate(DateUtil.parseDate(orderStartDateStr));
        }

        String orderEndDateStr = param.getOrderEndDateStr();
        if (StringUtils.hasText(orderEndDateStr)) {
            param.setOrderEndDate(DateUtil.parseDate(orderEndDateStr));
        }
        // 非总部设置权限
        boolean adminRole = mediaCommonService.isAdminRole();
        if (!adminRole) {
            param.setCreateBy(tbSysUserService.getCurrentSysUser().getUserCode());
        }// 有顺序关系
        // 执行状态
        if (MediaResourceConstant.ORDER_STATUS_TYPE.RUN.equals(param.getOrderStatus())) {

            param.setCurrentDate(new Date());
            //dto.setOrderEndDate(new Date());
        }
        // 已完成状态
        if (MediaResourceConstant.ORDER_STATUS_TYPE.DONE.equals(param.getOrderStatus())) {
            Date date = DateUtil.parseDate(DateUtil.simpleFormat(new Date()));
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.add(Calendar.DAY_OF_MONTH, 0);//+1今天的时间加一天
            Date time = calendar.getTime();
            param.setOrderEndDate(time);
            param.setOrderStatus(MediaResourceConstant.ORDER_STATUS_TYPE.RUN);
        }

        param.setPageSize(-1);
        List<MediaOrderDto> list = mediaOrderService.selectList(param);

        ServletOutputStream outputStream;
        try {
            outputStream = response.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
            throw new ServiceException("获取io流失败");
        }
        // 响应处理
        response.setContentType("multipart/form-data");
        String fileName = "export.xlsx";
        try {
            fileName = URLEncoder.encode("订单明细" + ".xlsx", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
        mediaOrderExportHandle.exportItem(list, "订单明细", outputStream);
    }

    /**
     * 废弃订单
     *
     * @param orderIds
     * @return
     */
    @PostMapping("/delOrder")
    public Result delOrder(String[] orderIds) {
        try {
            // 非总部设置权限
            boolean adminRole = mediaCommonService.isAdminRole();
            if (!adminRole) {
                throw new ServiceException("具有 media_admin 角色的人员才有该处理权限!");
            }
            if (orderIds.length == 0) {
                throw new ServiceException("废弃订单数不能为空!");
            }
           /* if (orderIds.length > 20) {
                throw new ServiceException("废弃的订单数一次不能超过20!");
            }*/
            List<String> orderIdList = Arrays.asList(orderIds);
            for (String s : orderIdList) {
                mediaOrderService.delById(s);
            }
            return Response.response(true);
        } catch (ServiceException e) {
            return Response.responseFail(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Response.responseFail("废弃订单异常！");
        }
    }
}
