package com.ym.mec.web.controller;

import com.ym.mec.auth.api.client.SysUserFeignService;
import com.ym.mec.auth.api.entity.SysUser;
import com.ym.mec.biz.dal.dao.*;
import com.ym.mec.biz.dal.dto.ReplacementInstrumentActivityStatDto;
import com.ym.mec.biz.dal.entity.*;
import com.ym.mec.biz.dal.enums.MessageTypeEnum;
import com.ym.mec.biz.dal.enums.YesOrNoEnum;
import com.ym.mec.biz.dal.page.ReplacementInstrumentActivityQueryInfo;
import com.ym.mec.biz.service.*;
import com.ym.mec.common.controller.BaseController;
import com.ym.mec.common.entity.HttpResponseResult;
import com.ym.mec.common.exception.BizException;
import com.ym.mec.common.page.PageInfo;
import com.ym.mec.thirdparty.message.MessageSenderPluginContext;
import com.ym.mec.util.date.DateUtil;
import com.ym.mec.util.excel.POIUtil;
import com.ym.mec.util.http.HttpUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

@RequestMapping("replacementInstrumentActivity")
@Api(tags = "乐器置换-调查问卷服务")
@RestController
public class ReplacementInstrumentActivityController extends BaseController {

    @Autowired
    private ReplacementInstrumentActivityService replacementInstrumentActivityService;
    @Autowired
    private SysUserFeignService sysUserFeignService;
    @Autowired
    private EmployeeDao employeeDao;
    @Autowired
    private ReplacementInstrumentActivityDao replacementInstrumentActivityDao;
    @Autowired
    private ReplacementInstrumentCooperationService replacementInstrumentCooperationService;
    @Autowired
    private SysConfigDao sysConfigDao;
    @Autowired
    private SysMessageService sysMessageService;
    @Autowired
    private GoodsService goodsService;

    @ApiOperation(value = "分页查询列表")
    @GetMapping("/queryPage")
    @PreAuthorize("@pcs.hasPermissions('replacementInstrumentActivity/queryPage')")
    public HttpResponseResult<PageInfo<ReplacementInstrumentActivityStatDto>> queryPage(ReplacementInstrumentActivityQueryInfo queryInfo) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed("用户信息获取失败");
        }
        Employee employee = employeeDao.get(sysUser.getId());
        if (StringUtils.isEmpty(queryInfo.getOrganId())) {
            queryInfo.setOrganId(employee.getOrganIdList());
        } else if (StringUtils.isEmpty(employee.getOrganIdList())) {
            return failed("用户所在分部异常");
        } else {
            List<String> list = Arrays.asList(employee.getOrganIdList().split(","));
            if (!list.containsAll(Arrays.asList(queryInfo.getOrganId().split(",")))) {
                return failed("非法请求");
            }
        }
        return succeed(replacementInstrumentActivityService.getPageList(queryInfo));
    }

    @ApiOperation(value = "统计信息查询")
    @GetMapping("/queryReplacementsStat")
    public HttpResponseResult<PageInfo<ReplacementInstrumentActivityStatDto>> queryReplacementsStat(ReplacementInstrumentActivityQueryInfo queryInfo) {
        return succeed(replacementInstrumentActivityService.queryReplacementsStat(queryInfo));
    }

    @ApiOperation(value = "统计信息查询")
    @GetMapping("/resultSync")
    public void resultSync() {
        replacementInstrumentActivityService.resultSync();
    }

    @ApiOperation(value = "修改")
    @PostMapping("/update")
    @PreAuthorize("@pcs.hasPermissions('replacementInstrumentActivity/update')")
    public HttpResponseResult<ReplacementInstrumentActivity> update(ReplacementInstrumentActivity replacementInstrumentActivity) {
        replacementInstrumentActivity.setGoodsId(replacementInstrumentActivity.getInstrumentsId());
        ReplacementInstrumentActivity oldReplacementInstrumentActivity = replacementInstrumentActivityDao.getLock(replacementInstrumentActivity.getId());
        if (!oldReplacementInstrumentActivity.getPayStatus().equals(0)) {
            return failed("支付中、已支付的乐器置换，不能修改");
        }

        ReplacementInstrumentCooperation byCooperationId = replacementInstrumentCooperationService.get(oldReplacementInstrumentActivity.getReplacementInstrumentCooperationId());
        if (byCooperationId.getOpenPay().equals(YesOrNoEnum.YES) && oldReplacementInstrumentActivity.getInstrumentsId() == null && replacementInstrumentActivity.getInstrumentsId() != null) {
            Goods goods = goodsService.get(replacementInstrumentActivity.getInstrumentsId());
            Map<Integer, String> userMap = new HashMap<>();
            Map<Integer, String> userPhoneMap = new HashMap<>();
            Integer userId = oldReplacementInstrumentActivity.getUserId();
            String baseApiUrl = sysConfigDao.findConfigValue("base_api_url");
            String pushUrl = baseApiUrl + "/#/questionGoodsSale?id=";
            userMap.put(userId, userId.toString());
            sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG, MessageTypeEnum.STUDENT_SMS_PUSH_REPLACEMENT_PAY,
                    userMap, null, 0, "5?" + pushUrl + replacementInstrumentActivity.getId(), "STUDENT", goods.getBrand(), "");

            userPhoneMap.put(userId, oldReplacementInstrumentActivity.getMobileNo());
            sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.AWSMS, MessageTypeEnum.STUDENT_SMS_PUSH_REPLACEMENT_PAY,
                    userPhoneMap, null, 0, null, null, goods.getBrand(), HttpUtil.getSortUrl(pushUrl + replacementInstrumentActivity.getId()));
        }

        oldReplacementInstrumentActivity.setSubjectId(replacementInstrumentActivity.getSubjectId());
        oldReplacementInstrumentActivity.setInstrumentsId(replacementInstrumentActivity.getInstrumentsId());
        oldReplacementInstrumentActivity.setGoodsId(replacementInstrumentActivity.getInstrumentsId());
        oldReplacementInstrumentActivity.setUpdateTime(new Date());
        replacementInstrumentActivityService.update(oldReplacementInstrumentActivity);

        return succeed(replacementInstrumentActivity);
    }

    @ApiOperation(value = "开启/关闭缴费")
    @PostMapping("/updateOpenFlag")
    @PreAuthorize("@pcs.hasPermissions('replacementInstrumentActivity/updateOpenFlag')")
    public HttpResponseResult<ReplacementInstrumentActivity> updateOpenFlag(Integer Id,Integer openFlag) {
        ReplacementInstrumentActivity replacementInstrumentActivity = replacementInstrumentActivityDao.getLock(Id);
        if (!replacementInstrumentActivity.getPayStatus().equals(0)) {
            return failed("支付中、已支付的乐器置换，不能修改");
        }

        if(replacementInstrumentActivity.getInstrumentsId() == null){
            return failed("修改失败：用户没有可置换商品");
        }
        if (openFlag == 1) {
            Goods goods = goodsService.get(replacementInstrumentActivity.getInstrumentsId());
            Map<Integer, String> userMap = new HashMap<>();
            Map<Integer, String> userPhoneMap = new HashMap<>();
            Integer userId = replacementInstrumentActivity.getUserId();
            String baseApiUrl = sysConfigDao.findConfigValue("base_api_url");
            String pushUrl = baseApiUrl + "/#/questionGoodsSale?id=";
            userMap.put(userId, userId.toString());
            sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG, MessageTypeEnum.STUDENT_SMS_PUSH_REPLACEMENT_PAY,
                    userMap, null, 0, "5?" + pushUrl + replacementInstrumentActivity.getId(), "STUDENT", goods.getBrand(), "");

            userPhoneMap.put(userId, replacementInstrumentActivity.getMobileNo());
            sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.AWSMS, MessageTypeEnum.STUDENT_SMS_PUSH_REPLACEMENT_PAY,
                    userPhoneMap, null, 0, null, null, goods.getBrand(), HttpUtil.getSortUrl(pushUrl + replacementInstrumentActivity.getId()));
        }

        replacementInstrumentActivity.setOpenFlag(openFlag);
        replacementInstrumentActivity.setUpdateTime(new Date());
        replacementInstrumentActivityService.update(replacementInstrumentActivity);
        return succeed(replacementInstrumentActivity);
    }

    @ApiOperation(value = "导出")
    @RequestMapping("/export")
    @PreAuthorize("@pcs.hasPermissions('replacementInstrumentActivity/export')")
    public void export(ReplacementInstrumentActivityQueryInfo queryInfo, HttpServletResponse response) throws Exception {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            throw new BizException("用户信息获取失败");
        }
        Employee employee = employeeDao.get(sysUser.getId());
        if (StringUtils.isEmpty(queryInfo.getOrganId())) {
            queryInfo.setOrganId(employee.getOrganIdList());
        } else if (StringUtils.isEmpty(employee.getOrganIdList())) {
            throw new BizException("用户所在分部异常");
        } else {
            List<String> list = Arrays.asList(employee.getOrganIdList().split(","));
            if (!list.containsAll(Arrays.asList(queryInfo.getOrganId().split(",")))) {
                throw new BizException("非法请求");
            }
        }
        queryInfo.setRows(99999);
        PageInfo<ReplacementInstrumentActivityStatDto> pageList = replacementInstrumentActivityService.getPageList(queryInfo);

        if (pageList.getTotal() <= 0) {
            throw new BizException("没有可导出的记录");
        }
        for (ReplacementInstrumentActivityStatDto row : pageList.getRows()) {
            if(row.getInstrumentsId() == null){
                row.setHasInstrumentsId("否");
            }else {
                row.setHasInstrumentsId("是");
            }
        }

        OutputStream outputStream = response.getOutputStream();
        HSSFWorkbook workbook = null;
        try {
            String[] header = {"活动编号","分部", "合作单位编号", "合作单位","问卷标题", "缴费状态", "学员编号", "学员姓名", "联系电话", "声部", "品牌", "型号", "是否置换乐器","现金支付","余额支付"};
            String[] body = {"replacementInstrumentCooperationId","organName", "cooperationOrganId", "cooperationOrganName","title","payStatus==NULL || payStatus==0?'未缴费':payStatus==1?'缴费中':'已缴费'", "userId", "userName", "mobileNo", "subjectName", "brand", "specification","hasInstrumentsId","actualAmount","balance"};
            workbook = POIUtil.exportExcel(header, body, pageList.getRows());
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=replacement-" + DateUtil.getDate(new Date()) + ".xls");
            response.flushBuffer();
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.flush();
            workbook.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    workbook.close();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
