package com.ruoyi.ibs.list.controller;

import com.github.pagehelper.Page;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.page.TableDataPageInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.ibs.list.domain.*;
import com.ruoyi.ibs.list.service.ISysCampaignService;
import com.ruoyi.ibs.list.service.ISysCustAppointSupplementService;
import com.ruoyi.ibs.list.service.ISysGroupCustomerService;
import com.ruoyi.ibs.list.service.LowcodeVisstFeedbackModelService;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.rmi.ServerException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 活动Controller
 *
 * @author ruoyi
 * @date 2024-09-11
 */
@RestController
@Api("标签管理-客群圈选-活动管理")
@RequestMapping("/system/campaign")
public class SysCampaignController extends BaseController {
    @Autowired
    private ISysCampaignService sysCampaignService;
    @Autowired
    private ISysGroupCustomerService sysGroupCustomerService;

    @Autowired
    private LowcodeVisstFeedbackModelService     lowcodeVisstFeedbackModelService;

    @Autowired
    private ISysCustAppointSupplementService iSysCustAppointSupplementService;
    /**
     * 查询活动列表
     */
    //@PreAuthorize("@ss.hasPermi('system:campaign:list')")
    @GetMapping("/list")
    @Log(title = "走访-任务列表查询")
    @ApiOperation("任务列表查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "campaignName", value = "活动名称", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "custType", value = "客户类型 0个人，1商户，2企业", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "type", value = "任务类型 0我的任务，1推送给我任务，2其他任务", dataType = "String", dataTypeClass = String.class),

    })
    public TableDataPageInfo<SysCampaign> list(String campaignName, String custType, String type) {
        Page page= startPage();
        List<SysCampaign> list = sysCampaignService.selectSysCampaignList(campaignName,custType,type);
        return getDataTable(list,page);
    }


    @GetMapping("/listCampaign")
    @Log(title = "走访-添加已有客户到存量活动中")
    @ApiOperation("添加已有客户到存量活动中")
    public R<Object> listCampaign(@ApiParam("custType 客户类型") String custType){

        return R.ok(sysCampaignService.listCampaign(custType));
    }


    @GetMapping("/listDetail")
    @Log(title = "走访-任务详情查询")
    @ApiOperation("任务详情查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "campaignId", value = "活动id", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "custType", value = "客户类型 0个人，1商户，2企业", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "type", value = "任务类型 0我的任务，1推送任务，2其他任务,3清单二次分配跳转(只有支行需要)", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "userManagerId", value = "登录人id，777 表示完成2次待分配，888表示待认领 999表示取客户经理 ，只有推送给我的才传", dataType = "Long", dataTypeClass = Long.class),
    })
    public TableDataPageInfo<CustomerList> listDetail(String campaignId, CustomerList customerList, String type, Long userManagerId) {
        SysCampaign sysCampaign = sysCampaignService.selectSysCampaignByCampaignId(campaignId);
        List<CustomerList> list = new ArrayList<>();
        Page<Object> page = startPage();
        if (sysCampaign.getIsCooperate()){
            list = sysCampaignService.selectSysCoopCampaignListDetails(campaignId,customerList,type,userManagerId);
        }else{
            list = sysCampaignService.selectSysCampaignListDetails(campaignId,customerList,type,userManagerId);
        }
        list = list.stream().map(e->{
                   if(StringUtils.isNotNull(e.getGroupId())){
                       e.setGroupId(e.getGroupId().split(",")[0]);
                   }
            return e;
        }).collect(Collectors.toList());
        return getDataTable(list,page);
    }


//    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @PostMapping("/exportDataByCustIds")
    @Log(title = "走访-任务详情，导出指定客群客户列表")
    @ApiOperation("任务详情，导出指定客群客户列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "campaignId", value = "活动id", dataType = "String", dataTypeClass = String.class),
    })
    public void exportDataByCustIds(HttpServletResponse response, String campaignId,@RequestParam(value = "custIds") List<String> custIds) throws Exception
    {
        if (campaignId!=null&&custIds!=null&&custIds.size()>0){
            sysCampaignService.selectSysGroupCustomerListExportByCustIds(response,campaignId,custIds);
        }

    }


//    /**
//     * 导出活动列表
//     */
//    @PreAuthorize("@ss.hasPermi('system:campaign:export')")
//    @Log(title = "走访-活动", businessType = BusinessType.EXPORT)
//    @PostMapping("/export")
//    public void export(HttpServletResponse response, SysCampaign sysCampaign) {
//        List<SysCampaign> list = sysCampaignService.selectSysCampaignList(sysCampaign);
//        ExcelUtil<SysCampaign> util = new ExcelUtil<SysCampaign>(SysCampaign.class);
//        util.exportExcel(response, list, "活动数据");
//    }

    /**
     * 获取活动详细信息
     */
//    @PreAuthorize("@ss.hasPermi('system:campaign:query')")
    @GetMapping(value = "/{id}")
    @Log(title = "走访-查詢詳情")
    @ApiOperation("查詢詳情")
    public R<Object> getInfo(@PathVariable("id") String id) {
        return R.ok(sysCampaignService.selectSysCampaignById(id));
    }

    /**
     * 新增活动
     */
//    @PreAuthorize("@ss.hasPermi('system:campaign:add')")
    @Log(title = "走访-活动", businessType = BusinessType.INSERT)
    @ApiOperation("新增活动")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "groupIds", value = "分群id list", dataType = "List<String>", dataTypeClass = List.class),
            @ApiImplicitParam(name = "campaignName", value = "活动名称", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "campaignType", value = "活动类型", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "campaignDegree", value = "紧急程度,高，中，低", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "claimType", value = "认领类型，'0'强制认领，'1'可选认领", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "startTime", value = "活动开始时间，yyyy-MM-dd", dataType = "Date", dataTypeClass = Date.class),
            @ApiImplicitParam(name = "endTime", value = "活动结束时间，yyyy-MM-dd", dataType = "Date", dataTypeClass = Date.class),
            @ApiImplicitParam(name = "claimStartTime", value = "认领开始时间，yyyy-MM-dd", dataType = "Date", dataTypeClass = Date.class),
            @ApiImplicitParam(name = "claimEndTime", value = "认领结束时间，yyyy-MM-dd", dataType = "Date", dataTypeClass = Date.class),
            @ApiImplicitParam(name = "distributeType", value = "分配规则，'0'手动指定，'1'按照客户归属，'2'按行政网格归属（地址）以2开头,20为零售部行政网格归属,21为公司部，22为运管部,'3'随机平均分配,'4'按特色网格归属以4开头,40为零售部特色网格归属,41为公司部，42为运管部,'5'按虚拟网格归属，以5开头,50为零售部虚拟网格归属,51为公司部，52为运管部，以英文逗号隔开", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "userIds", value = "随机平均分配客户经理id列表"),
            @ApiImplicitParam(name = "executer", value = "执行人,0代表机构，1代表个人，2代表混合分配（只有总行创建时才需要传此字段）", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "createRole", value = "活动创建角色，0总行管理员，1支行管理员", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "taskType", value = "任务类型，0营销任务，1事务任务", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "checkTarget", value = "考核目标", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "taskIndex", value = "任务指标", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "reward", value = "奖励说明", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "feedBack", value = "反馈要求，无，签到签退，拍照，反馈记录", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "custType", value = "客户类型 0个人，1商户，2企业", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "virtualGridIds", value = "虚拟网格id列表，多个以,分隔", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "layerIds", value = "特色网格类型（菜场，商圈等）id，多个以,分隔", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "relatedModelId", value = "关联反馈模型id", dataType = "String", dataTypeClass = String.class),
    })
    @PostMapping("/add")
    public R<Object> add(@RequestBody  SysCampaign sysCampaign) throws ServerException {
        return R.ok(sysCampaignService.insertSysCampaign(sysCampaign, sysCampaign.getGroupIds()));
    }

    @Log(title = "走访-活动", businessType = BusinessType.INSERT)
    @ApiOperation("新增活动协作模式")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "groupIds", value = "分群id list", dataType = "List<String>", dataTypeClass = List.class),
            @ApiImplicitParam(name = "campaignName", value = "活动名称", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "campaignType", value = "活动类型", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "campaignDegree", value = "紧急程度,高，中，低", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "claimType", value = "认领类型，'0'强制认领，'1'可选认领", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "startTime", value = "活动开始时间，yyyy-MM-dd", dataType = "Date", dataTypeClass = Date.class),
            @ApiImplicitParam(name = "endTime", value = "活动结束时间，yyyy-MM-dd", dataType = "Date", dataTypeClass = Date.class),
            @ApiImplicitParam(name = "claimStartTime", value = "认领开始时间，yyyy-MM-dd", dataType = "Date", dataTypeClass = Date.class),
            @ApiImplicitParam(name = "claimEndTime", value = "认领结束时间，yyyy-MM-dd", dataType = "Date", dataTypeClass = Date.class),
            @ApiImplicitParam(name = "distributeType", value = "分配规则，'0'手动指定，'1'按照客户归属，'2'按行政网格归属（地址）以2开头,20为零售部行政网格归属,21为公司部，22为运管部,'3'随机平均分配,'4'按特色网格归属以4开头,40为零售部特色网格归属,41为公司部，42为运管部,'5'按虚拟网格归属，以5开头,50为零售部虚拟网格归属,51为公司部，52为运管部，以英文逗号隔开", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "userIds", value = "随机平均分配客户经理id列表"),
            @ApiImplicitParam(name = "executer", value = "执行人,0代表机构，1代表个人，2代表混合分配（只有总行创建时才需要传此字段）", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "createRole", value = "活动创建角色，0总行管理员，1支行管理员", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "taskType", value = "任务类型，0营销任务，1事务任务", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "checkTarget", value = "考核目标", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "taskIndex", value = "任务指标", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "reward", value = "奖励说明", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "feedBack", value = "反馈要求，无，签到签退，拍照，反馈记录", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "custType", value = "客户类型 0个人，1商户，2企业", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "virtualGridIds", value = "虚拟网格id列表，多个以,分隔", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "layerIds", value = "特色网格类型（菜场，商圈等）id，多个以,分隔", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "relatedModelId", value = "关联反馈模型id", dataType = "String", dataTypeClass = String.class),
    })
    @PostMapping("/add/coop")
    public R<Object> addCoopModel(@RequestBody  SysCampaign sysCampaign) throws ServerException {
        return R.ok(sysCampaignService.insertSysCooperateCampaign(sysCampaign, sysCampaign.getGroupIds()));
    }

    @Log(title = "走访-活动", businessType = BusinessType.UPDATE)
    @ApiOperation("判断活动名称是否重复")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "campaignName", value = "客群名称,若重复，返回false,不重复,返回true", dataType = "String", dataTypeClass = String.class),
    })
    @GetMapping("/isGroupNameRepeat")
    public Boolean selectGroupName(String campaignName)
    {
        int count = sysCampaignService.selectByCampaignName(campaignName);
        Boolean flag = true;
        if (count>0){
            flag = false;
        }
        return flag;
    }

    @Log(title = "走访-分配客群", businessType = BusinessType.INSERT)
    @ApiOperation("支行二次推送客群")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "groupId", value = "分群id", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "campaignId", value = "总行创建的活动id(只有在支行推荐给我的客群二次推送时需要传此id)", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "distributeType", value = "分配规则，'0'手动指定，'1'按照客户归属，'2'按行政网格归属（地址）以2开头,20为零售部行政网格归属,21为公司部，22为运管部,'3'随机平均分配,'4'按特色网格归属以4开头,40为零售部特色网格归属,41为公司部，42为运管部,'5'按虚拟网格归属，以5开头,50为零售部虚拟网格归属,51为公司部，52为运管部，以英文逗号隔开", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "userIds", value = "随机平均分配客户经理id列表,只有选择随机平均分配方式时才需要传值"),
            @ApiImplicitParam(name = "virtualGridIds", value = "虚拟网格id列表，多个以,分隔", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "layerIds", value = "特色网格类型（菜场，商圈等）id，多个以,分隔", dataType = "String", dataTypeClass = String.class),
    })
    @PostMapping("/allocate")
    public AjaxResult allocate(@RequestBody SysCampaignSecondVo sysCampaignSecondVo) throws ServerException {
        if (sysCampaignSecondVo.getDistributeType()==null||"".equals(sysCampaignSecondVo.getDistributeType())){
            return error("请选择分配规则");
        }
        return sysCampaignService.insertSysCampaign(sysCampaignSecondVo.getGroupId(),sysCampaignSecondVo.getCampaignId(),sysCampaignSecondVo.getDistributeType(),sysCampaignSecondVo.getUserIds(),sysCampaignSecondVo.getVirtualGridIds(),sysCampaignSecondVo.getLayerIds(),sysCampaignSecondVo);
    }

    /**
     * 修改活动
     */
    @PreAuthorize("@ss.hasPermi('system:campaign:edit')")
    @Log(title = "走访-活动", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysCampaign sysCampaign) {
        return toAjax(sysCampaignService.updateSysCampaign(sysCampaign));
    }

    /**
     * 删除活动
     */
    @PreAuthorize("@ss.hasPermi('system:campaign:remove')")
    @Log(title = "走访-活动", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(sysCampaignService.deleteSysCampaignByIds(ids));
    }

    /**
     * 根据活动id查询当前活动
     */
//    @PreAuthorize("@ss.hasPermi('system:campaign:list')")
    @GetMapping("/getCampaignByCampaignId")
    @ApiOperation("根据活动id查询活动详情")
    @Log(title = "走访-根据活动id查询活动详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "campaignId", value = "总行创建的活动id(只有在支行推荐给我的客群二次推送时需要传此id)", dataType = "String", dataTypeClass = String.class),
    })
    public SysCampaign executer(String campaignId) {

        return sysCampaignService.selectSysCampaignByCampaignId(campaignId);
    }


    /**
     * 根据活动id查询当前活动
     */
//    @PreAuthorize("@ss.hasPermi('system:campaign:list')")
    @GetMapping("/getCmpmByCustType")
    @ApiOperation("根据客户类型查询管户产品")
    @Log(title = "走访-根据客户类型查询管户产品")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "custType", value = "0个人，1商户，2企业", dataType = "String", dataTypeClass = String.class),
    })
    public Map<String,String> getCmpmByCustType(String custType) {

        return Constans.convertCmpm(custType);
    }

    /**
     * 查询走访名单列表
     */
    @GetMapping("/visitInfoList")
    @ApiOperation("pad走访记录列表")
    @Log(title ="pad走访记录列表")
    public TableDataPageInfo<VisitInfoVO> list(VisitInfoDTO visitInfoDTO) {
        Page<Object> page = startPage();
        List<VisitInfoVO> list = sysCampaignService.selectVisitInfoVoList(visitInfoDTO);
        return getDataTable(list, page);
    }

    @Log(title = "走访-反馈模板list", businessType = BusinessType.UPDATE)
    @GetMapping("/modelList")
    @ApiOperation("反馈模板list")
    public R<Map<String,String>> modelList(@RequestParam(name ="custType", required = true) String custType)
    {
        return R.ok((lowcodeVisstFeedbackModelService.modeList(null,null,null,custType)
                .stream().collect(HashMap::new, (m, v) -> m.put(v.getUuid(),v.getModelName()), HashMap::putAll)));
    }

    @PostMapping("/updateVisitInfoFeedback")
    @ApiOperation("更新PAD走访反馈")
    @Log(title ="pad走访记录-更新走访反馈", businessType = BusinessType.UPDATE)
    public AjaxResult updateVisitInfoFeedback(@RequestBody VisitInfoFeedbackUpdateDTO updateDTO) {
        return toAjax(sysCampaignService.updateVisitInfoFeedback(updateDTO));
    }

    @PostMapping("/delete")
    @ApiOperation("根据campaignId删除任务")
    @Log(title = "走访-根据campaignId删除任务")
    public R<Object> delete(@RequestBody SysCampaign sysCampaign) {
        if (StringUtils.isEmpty(sysCampaign.getCampaignId())){
            return R.fail("campaignId不能为空");
        }
        return R.ok(sysCampaignService.deleteSysCampaign(sysCampaign.getCampaignId()));
    }


    @GetMapping("/custAppointSupplement")
    @ApiOperation("定时任务重跑")
    @Log(title = "走访-定时任务重跑")
    public R<Object> custAppointSupplement() {
       iSysCustAppointSupplementService.custAppointSupplement(new ArrayList<>());
       return R.ok();
    }


}
