package com.sifang.modules.customer.controller;

import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.Service.CrmCustomerEntryWeeklyRecordService;
import com.sifang.modules.customer.entity.CrmCustomerEntryWeeklyRecord;
import com.sifang.modules.customer.excel.FileExportUtil;
import com.sifang.modules.customer.excel.WeeklyRecodeExcel;
import com.sifang.modules.sunshine.SystemSetting.utils.BusinessException;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.entity.Operator;
import com.sifang.modules.sys.util.CrmUtils;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sys.web.BaseController;
import com.sifang.modules.task.WeeklyRecordTask;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;


@Controller
@RequestMapping(value = "${adminPath}/customerEntryWeeklyRecord")
public class CrmCustomerEntryWeeklyRecordController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(CrmCustomerEntryWeeklyRecord.class);
    @Autowired
    private CrmCustomerEntryWeeklyRecordService weeklyRecordService;


    /**
     * 获取上周日期 拼成 "2024-05-20~2024-05-26"格式
     * @return
     */
    public String getLastWeekTime(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.setFirstDayOfWeek(Calendar.MONDAY); // 设置每周的第一天为星期一
        calendar.add(Calendar.WEEK_OF_YEAR, -1); // 减去一周
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); // 设置为星期一
        Date lastWeekStartDate = calendar.getTime();
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY); // 设置为星期日
        Date lastWeekEndDate = calendar.getTime();
        String time = sdf.format(lastWeekStartDate) + "~" + sdf.format(lastWeekEndDate);
        return time;
    }

    @RequestMapping(value = "weeklyRecordList")
    public String weeklyRecordList(Model model){
        model.addAttribute("time",getLastWeekTime());
        return "modules/yangguang/customer/entry/provincialStatistics/weeklyRecordList";
    }
    /**
     *   列表数据  getWeeklyRecordListData
     */
    @ResponseBody
    @RequestMapping("/getWeeklyRecordListData")
    public Object getWeeklyRecordListData(HttpServletRequest request){
        LayuiPage<Record> page = new LayuiPage<>(request);
        Map<String, String> params = getParams(request);
        User user = UserUtils.getUser();
        Operator operator = Operator.of(user.getId(), CrmUtils.getUserXM(user),user.getUserType());
        return weeklyRecordService.getPageData(page,params,operator);
    }

    /**
     * 去同步周报页面
     */
    @RequestMapping(value = "toSyncWeeklyRecord")
    public String toSyncWeeklyRecord(Model model){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.setFirstDayOfWeek(Calendar.MONDAY); // 设置每周的第一天为星期一
        calendar.add(Calendar.WEEK_OF_YEAR, -1); // 减去一周
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); // 设置为星期一
        Date lastWeekStartDate = calendar.getTime();
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY); // 设置为星期日
        Date lastWeekEndDate = calendar.getTime();
        model.addAttribute("startDate",sdf.format(lastWeekStartDate));
        model.addAttribute("endDate",sdf.format(lastWeekEndDate));
        model.addAttribute("time",getLastWeekTime());
        return "modules/yangguang/customer/entry/provincialStatistics/syncWeeklyRecord";
    }
    /**
     * 同步周报
     */
    @ResponseBody
    @RequestMapping("/syncWeeklyRecord")
    public Result syncWeeklyRecord(String startDate,String endDate){
        WeeklyRecordTask weeklyRecordTask = new WeeklyRecordTask();
        weeklyRecordTask.syncWeeklyRecord(startDate,endDate);
        return Result.ok();
    }


    /**
     * 导出excel
     */
    @RequestMapping(value = "exportExcel")
    public void exportExcel(HttpServletRequest request, HttpServletResponse response){
        String creatTime = request.getParameter("creatTime");
        if (StringUtils.isBlank(creatTime)){
            throw new BusinessException("时间不能为空");
        }
        String[] times = creatTime.split("~");
        String startDate =  times[0];
        String endDate = times[1];
        List<Record> weeklyRecords = weeklyRecordService.getWeeklyRecordsByDate(startDate,endDate);
        List<WeeklyRecodeExcel> list = new ArrayList<>();
        for (Record record : weeklyRecords) {
            WeeklyRecodeExcel excel = new WeeklyRecodeExcel();
            excel.setProvince(record.getStr("province"));
            excel.setLeaderName(record.getStr("leader_name"));
            excel.setSignedCntWeek(record.getBigDecimal("signed_cnt_week"));
            excel.setCumSignedCnt(record.getBigDecimal("cum_signed_cnt"));
            excel.setShippedCntWeekTarget(null);
            excel.setShippedCntWeek(record.getBigDecimal("shipped_cnt_week"));
            excel.setShippedCntWeekPropRate(null);
            excel.setShippedCntMonth(record.getBigDecimal("shipped_cnt_month"));
            excel.setShippedCntYear(record.getBigDecimal("shipped_cnt_year"));
            excel.setAppCntWeek(record.getBigDecimal("app_cnt_week"));
            excel.setAppCntMonth(record.getBigDecimal("app_cnt_month"));
            excel.setAppCntYear(record.getBigDecimal("app_cnt_year"));
            excel.setSubmittedWeek(record.getBigDecimal("submitted_week"));
            excel.setSubmittedMonthTarget(null);
            excel.setSubmittedMonth(record.getBigDecimal("submitted_month"));
            excel.setSubmittedMonthTarget(null);
            excel.setSubmittedYear(record.getBigDecimal("submitted_year"));
            excel.setFinalApprovedWeek(record.getBigDecimal("final_approved_week"));
            excel.setFinalApprovedMonth(record.getBigDecimal("final_approved_month"));
            excel.setFinalApprovedYear(record.getBigDecimal("final_approved_year"));
            excel.setGridConnectedWeek(record.getBigDecimal("grid_connected_week"));
            excel.setGridConnectedMonth(record.getBigDecimal("grid_connected_month"));
            excel.setGridConnectedYear(record.getBigDecimal("grid_connected_year"));

            list.add(excel);
        }
        FileExportUtil.exportWeeklyRecodeExcel(list,response,startDate,endDate);
    }


}
