package com.huiju.estateagents.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huiju.estateagents.base.BaseController;
import com.huiju.estateagents.base.ResponseBean;
import com.huiju.estateagents.common.CommConstant;
import com.huiju.estateagents.common.StringUtils;
import com.huiju.estateagents.entity.*;
import com.huiju.estateagents.event.EventBus;
import com.huiju.estateagents.service.ITaDocumentImgService;
import com.huiju.estateagents.service.ITaDocumentVerifyService;
import com.huiju.estateagents.service.ITaPersonService;
import io.swagger.models.auth.In;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
    * 资料审核  前端控制器
    * </p>
 *
 * @author jobob
 * @since 2019-10-23
 */
@RestController
@RequestMapping("/api")
public class TaDocumentVerifyController extends BaseController {

    private final Logger logger = LoggerFactory.getLogger(TaDocumentVerifyController.class);

    @Autowired
    public ITaDocumentVerifyService iTaDocumentVerifyService;

    @Autowired
    public ITaPersonService taPersonService;

    @Autowired
    public ITaDocumentImgService documentImgService;


    @Autowired
    private ApplicationContext applicationContext;

    /**
     * 分页查询列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value="/admin/documentVerify",method= RequestMethod.GET)
    public ResponseBean documentVerifyList(@RequestParam(value ="pageNum",defaultValue = "1") Integer pageNum,
                                           @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize,
                                           @RequestParam(value ="name",required = false) String name,
                                           @RequestParam(value ="tel",required = false) String tel,
                                           @RequestParam(value = "startDate",required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)LocalDateTime startDate,
                                           @RequestParam(value = "endDate",required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)LocalDateTime endDate,
                                           HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean = iTaDocumentVerifyService.getAdminDocumentList(pageNum,pageSize,name,tel,getOrgId(request),startDate,endDate);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("documentVerifyList -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 微信查询我的审核列表
     * @return
     */
    @RequestMapping(value="/wx/documentVerify/list",method= RequestMethod.GET)
    public ResponseBean wxDocumentVerifyList(HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        Integer orgId = getOrgId(request);
        String openid = getOpenId(request);
        List<TaPerson> taPersons = taPersonService.getPersonsByOpenId(openid);
        if (null == taPersons || taPersons.size() != 1) {
            return responseBean.error("验证人员信息失败", ResponseBean.ERROR_UNAVAILABLE);
        }
        TaPerson person = taPersons.get(0);
        try {
            QueryWrapper<TaDocumentVerify> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("person_id",person.getPersonId());
            queryWrapper.eq("org_id",orgId);
            queryWrapper.orderByAsc("verify_status");
            List<TaDocumentVerify>result = iTaDocumentVerifyService.list(queryWrapper);
            responseBean.addSuccess(result);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("documentVerifyList -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 保存对象
     * @param documentVerify List<TaDocumentImg>
     * @return
     */
    @RequestMapping(value="/wx/documentVerify",method= RequestMethod.POST)
    public ResponseBean wxDocumentVerifyAdd(@RequestBody TaDocumentVerify documentVerify, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        Integer orgId = getOrgId(request);
        String openid = getOpenId(request);
        List<TaPerson> taPersons = taPersonService.getPersonsByOpenId(openid);
        if (null == taPersons || taPersons.size() != 1) {
            return responseBean.error("验证人员信息失败", ResponseBean.ERROR_UNAVAILABLE);
        }
        TaPerson person = taPersons.get(0);
        documentVerify.setCreateDate(LocalDateTime.now());
        documentVerify.setOrgId(orgId);
        documentVerify.setPersonId(person.getPersonId());
        documentVerify.setStatus(CommConstant.STATUS_NORMAL);
        documentVerify.setVerifyStatus(CommConstant.VERIFY_READY);
        List<TaDocumentImg>list = documentVerify.getImgList();
        try {
            if (iTaDocumentVerifyService.save(documentVerify)){
                for(int i =0; i<list.size();i++){
                    list.get(i).setCreateDate(LocalDateTime.now());
                    list.get(i).setDocumentVerifyId(documentVerify.getDocumentVerifyId());
                    list.get(i).setOrgId(orgId);
                    list.get(i).setPersonId(person.getPersonId());
                }
                documentImgService.saveBatch(list);
                documentVerify.setImgList(list);
                responseBean.addSuccess(documentVerify);

            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("documentVerifyAdd -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id删除对象
     * @param id  实体ID
     */
    @ResponseBody
    @RequestMapping(value="/documentVerify/{id}", method= RequestMethod.DELETE)
    public ResponseBean documentVerifyDelete(@PathVariable Integer id){
        ResponseBean responseBean = new ResponseBean();
        try {
            if(iTaDocumentVerifyService.removeById(id)){
                responseBean.addSuccess("success");
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("documentVerifyDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 微信查询对象
     * @return
     */
    @RequestMapping(value="/wx/documentVerify/{id}",method= RequestMethod.GET)
    public ResponseBean wxDocumentVerifyGetThis(@PathVariable Integer id,HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        Integer orgId = getOrgId(request);
        TaDocumentVerify verify = iTaDocumentVerifyService.getById(id);
        if (null != verify) {
            QueryWrapper<TaDocumentImg> documentImgQueryWrapper = new QueryWrapper<>();
            documentImgQueryWrapper.eq("document_verify_id", verify.getDocumentVerifyId());
            documentImgQueryWrapper.eq("person_id", verify.getPersonId());
            documentImgQueryWrapper.eq("org_id", orgId);
            List<TaDocumentImg> documentImgList = documentImgService.list(documentImgQueryWrapper);
            verify.setImgList(documentImgList);
        }

        responseBean.addSuccess(verify);
        return responseBean;
    }

    /**
     * 微信修改对象
     * @param id  实体ID
     * @return
     */
    @RequestMapping(value="/wx/documentVerify/{id}",method= RequestMethod.PUT)
    public ResponseBean wxDocumentVerifyUpdate(@PathVariable Integer id,
                                               @RequestBody TaDocumentVerify documentVerify,
                                               HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        Integer orgId = getOrgId(request);
        String openid = getOpenId(request);
        List<TaPerson> taPersons = taPersonService.getPersonsByOpenId(openid);
        if (null == taPersons || taPersons.size() != 1) {
            return responseBean.error("验证人员信息失败", ResponseBean.ERROR_UNAVAILABLE);
        }
        TaPerson person = taPersons.get(0);
        documentVerify.setDocumentVerifyId(id);
        documentVerify.setVerifyStatus(CommConstant.VERIFY_READY);
        List<TaDocumentImg>list = documentVerify.getImgList();
        try {
            if (iTaDocumentVerifyService.updateById(documentVerify)){
                QueryWrapper<TaDocumentImg>queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("document_verify_id",documentVerify.getDocumentVerifyId());
                documentImgService.remove(queryWrapper);
                for(int i =0; i<list.size();i++){
                    list.get(i).setCreateDate(LocalDateTime.now());
                    list.get(i).setDocumentVerifyId(documentVerify.getDocumentVerifyId());
                    list.get(i).setOrgId(orgId);
                    list.get(i).setPersonId(person.getPersonId());
                }
                documentImgService.saveBatch(list);
                documentVerify.setImgList(list);
                responseBean.addSuccess(documentVerify);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("documentVerifyUpdate -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 修改对象
     * @param id  实体ID
     * @param documentVerify 实体对象
     * @return
     */
    @RequestMapping(value="/admin/documentVerify/{id}",method= RequestMethod.PUT)
    public ResponseBean documentVerifyUpdate(@PathVariable Integer id,
                                             @RequestBody TaDocumentVerify documentVerify,
                                             HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        if (documentVerify.getVerifyStatus().equals(CommConstant.STATUS_NORMAL)){
            Integer userId = getUserId(request);
            documentVerify.setVerifyUser(userId.toString());
        }
        try {
            documentVerify.setDocumentVerifyId(id);
            if (iTaDocumentVerifyService.updateById(documentVerify)){

                if (null != documentVerify.getVerifyStatus() && documentVerify.getVerifyStatus().intValue() == 1) {
                    // 活动核销加积分
                    TaDocumentVerify verify = iTaDocumentVerifyService.getById(documentVerify.getDocumentVerifyId());

                    // 资料审核加积分
                    applicationContext.publishEvent(new EventBus(verify, EventBus.EventType.DocumentVerify,verify.getOrgId()));

                }

                responseBean.addSuccess(documentVerify);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("documentVerifyUpdate -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id查询对象
     * @param id  实体ID
     */
    @RequestMapping(value="/admin/documentVerify/{id}",method= RequestMethod.GET)
    public ResponseBean documentVerifyGet(@PathVariable String id,
                                          @RequestParam(value ="pageNum",defaultValue = "1") Integer pageNum,
                                          @RequestParam(value ="pageSize",defaultValue = "5") Integer pageSize,
                                          HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            IPage<TaDocumentVerify> documentVerify = iTaDocumentVerifyService.getDocumentVerifyList(pageNum,pageSize,id,getOrgId(request));
            responseBean.addSuccess(documentVerify);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("documentVerifyDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }
}
