package com.fs.app.controller;

import com.fs.app.annotation.Login;
import com.fs.app.annotation.NoRepeatSubmit;
import com.fs.common.annotation.Log;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.domain.R;
import com.fs.common.core.page.TableDataInfo;
import com.fs.common.enums.BusinessType;
import com.fs.common.exception.CustomException;
import com.fs.company.mapper.CompanyUserRoleMapper;
import com.fs.course.param.CollectConfirmGeneratePrescribeParam;
import com.fs.course.param.CollectionBindUserParam;
import com.fs.course.param.CollectionInfoConfirmParam;
import com.fs.course.param.SubmitCollectionAnswerParam;
import com.fs.course.vo.FsUserInfoCollectionUVO;
import com.fs.enums.PostPayPrescStatusEnum;
import com.fs.his.domain.FsUser;
import com.fs.his.domain.FsUserInformationCollectionSchedule;
import com.fs.his.enums.PrescriptionTaskStepEnum;
import com.fs.his.service.IFsPackageService;
import com.fs.his.service.IFsUserService;
import com.fs.his.vo.OptionsVO;
import com.fs.his.vo.PostPayPrescStatusVo;
import com.fs.hisStore.domain.FsUserInformationCollection;
import com.fs.hisStore.param.FsUserInformationCollectionParam;
import com.fs.hisStore.service.IFsUserInformationCollectionService;
import com.fs.qw.service.IFsUserInformationCollectionScheduleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;
@Slf4j
@Api("用户信息采集接口")
@RestController
@RequestMapping(value="/app/collection")
public class UserInfoCollectionController extends AppBaseController {

    @Autowired
    private IFsPackageService fsPackageService;

    @Autowired
    private IFsUserService userService;

    @Autowired
    private IFsUserInformationCollectionService userInformationCollectionService;

    @Autowired
    private IFsUserInformationCollectionScheduleService fsUserInformationCollectionScheduleService;

    @Autowired
    private CompanyUserRoleMapper roleMapper;

    @ApiOperation("用户信息采集详情")
    @GetMapping("/getInfo")
    public R getInfo(@RequestParam("id") Long id) {
        Long userId = Long.parseLong(getUserId());
        FsUserInfoCollectionUVO info = userInformationCollectionService.info(id,userId);
        return R.ok().put("data",info);
    }

    @ApiOperation("确认用户采集信息")
    @PostMapping("/confirm")
    public R confirm(@RequestBody CollectionInfoConfirmParam param) {
        param.setUserId(Long.parseLong(getUserId()));
        return userInformationCollectionService.userConfirm(param);
    }

    @ApiOperation("个微版信息采集用户确认并生成待开处方")
    @NoRepeatSubmit(expire = 2, message = "请勿重复点击，正在处理中...")
    @PostMapping("/confirmGeneratePrescription")
    public R confirmGeneratePrescription(@RequestBody CollectConfirmGeneratePrescribeParam param) {
        param.setUserId(Long.parseLong(getUserId()));
        return userInformationCollectionService.generateFormalPrescription(param);
    }

    @ApiOperation("绑定用户信息")
    @PostMapping("/bindUser")
    public R bindUser(@RequestBody CollectionBindUserParam param) {
        param.setUserId(Long.parseLong(getUserId()));
        return userInformationCollectionService.bindUser(param);
    }

    /**
     * 获取所有处方流程状态枚举信息
     * 返回格式适合前端使用，包含code和desc
     */
    @ApiOperation("获取所有处方流程状态枚举信息")
    @GetMapping(value = "/all")
    public R getAllStatus() {
        List<PostPayPrescStatusVo> statusList = new ArrayList<>();

        for (PostPayPrescStatusEnum status : PostPayPrescStatusEnum.values()) {
            if (!status.equals(PostPayPrescStatusEnum.UNKNOWN)) {
                statusList.add(new PostPayPrescStatusVo(status.getCode(), status.getDesc()));
            }
        }

        return R.ok().put("data", statusList);
    }

    /**
     * 获取用户信息采集详细信息
     */
    @ApiOperation("获取用户信息采集详细信息")
    @GetMapping(value = "/detail")
    public R detail(FsUserInformationCollection param)
    {
        return R.ok().put("data", userInformationCollectionService.getInfo(param));
    }

    /**
     * 新增用户信息采集
     */
    @ApiOperation("新增用户信息采集")
    @Log(title = "用户信息采集", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public R add(@RequestBody FsUserInformationCollectionParam fsUserInformationCollection)
    {
//        FsUser user=userService.selectFsUserByUserId(Long.parseLong(getUserId()));
//        fsUserInformationCollection.setCompanyUserId(user.getCompanyUserId());
//        fsUserInformationCollection.setCompanyId(user.getCompanyId());
        Long l = userInformationCollectionService.insertFsUserInformationCollection(fsUserInformationCollection);
        if (l > 0) {
            return R.ok();

        } else {
            return R.error();
        }
    }

    /**
     * 提交用户填写采集信息问题(只有用户自主填写完采集信息时才调用)
     * */
    @ApiOperation("提交用户填写采集信息问题")
    @PostMapping("/submitCollectionAnswerParam")
    public R submitCollectionAnswerParam(@RequestBody SubmitCollectionAnswerParam param)
    {
        param.setUserId(Long.parseLong(getUserId()));
        int result = userInformationCollectionService.submitCollectionAnswerParam(param);
        if (result > 0) {
            return R.ok();
        } else {
            return R.error();
        }
    }

    /**
     * 修改用户信息采集
     */
    @ApiOperation("修改用户信息采集")
    @Log(title = "用户信息采集", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public R edit(@RequestBody FsUserInformationCollectionParam fsUserInformationCollection)
    {
//        FsUser user=userService.selectFsUserByUserId(Long.parseLong(getUserId()));
//        fsUserInformationCollection.setCompanyUserId(user.getCompanyUserId());
//        fsUserInformationCollection.setCompanyId(user.getCompanyId());
        Long l = userInformationCollectionService.updateFsUserInformationCollection(fsUserInformationCollection);
        if (l > 0) {
            return R.ok();

        } else {
            return R.error();
        }
    }

    /**
     * 查询销售是否具有代填权限
     * */
    @GetMapping("/getSalesHasCollectionPermission")
    public AjaxResult getSalesHasCollectionPermission(){
        boolean salesProxyFillConfig = userInformationCollectionService.getSalesProxyFillConfig();
        return AjaxResult.success(salesProxyFillConfig);
    }


    /**
     * 对于每条用户信息采集记录，只获取其最新的任务流程
     */
    @GetMapping("/schedule/list")
    public TableDataInfo list(FsUserInformationCollectionSchedule fsUserInformationCollectionSchedule)
    {
        Long companyUserId=getCompanyUserId();
        if (companyUserId!=null){
            fsUserInformationCollectionSchedule.setCompanyUserId(companyUserId);
            //管理员查看所有数据
            Long isAdmin = roleMapper.companyUserIsAdmin(getCompanyUserId());
            if (isAdmin != null) {
                fsUserInformationCollectionSchedule.setCompanyUserId(null);
            }
            startPage();
            List<FsUserInformationCollectionSchedule> list = fsUserInformationCollectionScheduleService.getUserRecordLatestTaskProcess(fsUserInformationCollectionSchedule);
            return getDataTable(list);
        }
        log.info("未查询到登录用户，用户信息采集列表获取失败");
        return getDataTable(null);
    }

    /**
     * 停止用户信息采集任务
     */
    @PutMapping("/schedule/stop")
    public R stop(@RequestBody FsUserInformationCollectionSchedule param){
        FsUser user=userService.selectFsUserByUserId(Long.parseLong(getUserId()));
        return userInformationCollectionService.stopCollection(param,user.getCompanyUserId(),1);
    }
    /**
     * 微信小程序获取用户信息采集任务流程步骤枚举列表
     */
    @GetMapping("/schedule/steps")
    public AjaxResult getTaskSteps() {
        List<Map<String, Object>> steps = Arrays.stream(PrescriptionTaskStepEnum.values())
                .map(enumItem -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("dictValue", enumItem.getCode());
                    map.put("dictLabel", enumItem.getDesc());
                    return map;
                })
                .collect(Collectors.toList());
        return AjaxResult.success(steps);
    }

    /**
     * 查询私有套餐包列表
     */
    @GetMapping("/schedule/privatePackageList")
    public TableDataInfo selectAllPrivatePackageList()
    {
        List<OptionsVO> list = fsPackageService.selectAllPrivatePackageList();
        return getDataTable(list);
    }

    @PostMapping("/salesHelpConfirm")
    public R salesHelpConfirm(@RequestBody FsUserInformationCollectionSchedule param){
        if (param.getCollectionId() == null) {
            return R.error("collectionId不能为空");
        }
        if (param.getCompanyUserId() == null) {
            return R.error("companyUserId不能为空");
        }
        return userInformationCollectionService.salesHelpConfirm(param.getCollectionId(),param.getCompanyUserId());
    }


    //APP---查询用户是否有信息采集数据
    @Login
    @ApiOperation("app获取用户是否有信息采集")
    @GetMapping("/hasUserCollectionInfo")
    public R hasUserCollectionInfo(){
        long userId = Long.parseLong(getUserId());
        log.info("查询APP用户信息采集，用户id：{}",userId);
        userInformationCollectionService.hasUserCollectionInfo(userId);
        return R.ok();
    }

    @Login
    @ApiOperation("app添加用户信息采集")
    @PostMapping("/addUserCollection")
    public R addUserCollection(@RequestBody FsUserInformationCollectionParam param){
        Long userId = Long.parseLong(getUserId());
        param.setUserId(userId);
        return userInformationCollectionService.addUserCollection(param);
    }
}
