package com.gic.haoban.manage.web.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gic.api.base.commons.Page;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.clerk.api.dto.ClerkDTO;
import com.gic.clerk.api.service.ClerkService;
import com.gic.commons.util.EntityUtil;
import com.gic.commons.webapi.reponse.RestResponse;
import com.gic.haoban.base.api.common.BasePageInfo;
import com.gic.haoban.base.api.common.PageResult2;
import com.gic.haoban.base.api.common.pojo.dto.WellDoneLoginDTO;
import com.gic.haoban.common.anno.HttpLimit;
import com.gic.haoban.common.utils.HaobanResponse;
import com.gic.haoban.common.utils.PageUtil;
import com.gic.haoban.manage.api.dto.AuditDTO;
import com.gic.haoban.manage.api.dto.StaffClerkBindLogDetailDTO;
import com.gic.haoban.manage.api.dto.StaffClerkRelationDTO;
import com.gic.haoban.manage.api.dto.StaffDTO;
import com.gic.haoban.manage.api.enums.AuditType;
import com.gic.haoban.manage.api.enums.ChannelCodeEnum;
import com.gic.haoban.manage.api.service.*;
import com.gic.haoban.manage.web.errCode.HaoBanErrCode;
import com.gic.haoban.manage.web.vo.AuditVO;
import com.gic.haoban.manage.web.vo.StaffClerkBindLogDetailVO;
import com.gic.redis.data.util.RedisUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;


@RestController
public class AuditController extends WebBaseController {

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

    @Autowired
    private AuditApiService auditApiService;
    @Autowired
    private StaffClerkRelationApiService staffClerkRelationApiService;
    @Autowired
    private StaffApiService staffApiService;
    @Autowired
    private SyncHaobanToGicApiService syncHaobanToGicApiService;
    @Autowired
    private StaffDepartmentRelatedApiService staffDepartmentRelatedApiService;
    @Autowired
    private ClerkService clerkService;

    //关联记录列表
    @RequestMapping("clerk-apply-list")
    public HaobanResponse staffStoreList(String staffId, Integer auditType, Integer auditStatus, String enterpriseId, String wxEnterpriseId, BasePageInfo pageInfo) {
        if (StringUtils.isAnyBlank(staffId, wxEnterpriseId)) {
            return resultResponse(HaoBanErrCode.ERR_2);
        }

        Page<AuditDTO> page = auditApiService.listByStaffId(staffId, auditType, auditStatus, enterpriseId, pageInfo);
        List<AuditDTO> list = page.getResult();
        List<AuditVO> voList = new ArrayList<AuditVO>();
        for (AuditDTO auditDTO : list) {
            AuditVO vo = EntityUtil.changeEntityByJSON(AuditVO.class, auditDTO);
            String clerkCode = "";
            String staffName = "";
            String oldValue = auditDTO.getOldValue();
            JSONObject json = JSON.parseObject(oldValue);
            clerkCode = json.getString("clerkCode");
            staffName = json.getString("staffName");
            if (auditDTO.getAuditType() == 3) {
                vo.setCommitReason("添加导购账号：(" + clerkCode + ")");
            } else if (auditDTO.getAuditType() == 4) {
                vo.setCommitReason("删除导购账号：(" + clerkCode + ")");
            } else {
                vo.setCommitReason("绑定申请{" + staffName + "}绑定登录导购code " + clerkCode);
            }
            voList.add(vo);
        }
        Page<AuditVO> pageVO = new Page<>();
        pageVO.setCurrentPage(page.getCurrentPage());
        pageVO.setPageSize(page.getPageSize());
        pageVO.setResult(voList);
        pageVO.setTotalCount(page.getTotalCount());
        pageVO.setTotalPage(page.getTotalPage());
        PageResult2 pageResult2 = PageUtil.getPageInfo(pageVO);
        return resultResponse(HaoBanErrCode.ERR_1, pageResult2);

    }

    /**
     * @param wxEnterpriseId 微信企业Id
     * @param clerkId        导购Id
     * @param enterpriseId   企业Id
     * @param optType        操作类型 0 绑定 1解绑 默认传 1
     * @param pageInfo       页面
     * @return
     */
    @RequestMapping("clerk-unbind-list")
    public HaobanResponse staffUnbindList(String wxEnterpriseId, String clerkId, String enterpriseId, @RequestParam(defaultValue = "1") Integer optType, BasePageInfo pageInfo) {
        Page<StaffClerkBindLogDetailDTO> page = staffClerkRelationApiService.pageStaffClerkUnBindLog(wxEnterpriseId, clerkId, enterpriseId, optType, pageInfo);
        if (page == null) {
            return resultResponse(HaoBanErrCode.ERR_8);
        }
        List<StaffClerkBindLogDetailDTO> list = page.getResult();
        List<StaffClerkBindLogDetailVO> voList = new ArrayList<StaffClerkBindLogDetailVO>();
        for (StaffClerkBindLogDetailDTO staffClerkBindLogDetailDTO : list) {
            if (staffClerkBindLogDetailDTO.getChannelCode() != ChannelCodeEnum.AUDIT_BIND.getCode()) {
                StaffClerkBindLogDetailVO vo = EntityUtil.changeEntityByJSON(StaffClerkBindLogDetailVO.class, staffClerkBindLogDetailDTO);
                vo.setUnbindReason(ChannelCodeEnum.getNameByCode(vo.getChannelCode()));
                voList.add(vo);
            }
        }
        Page<StaffClerkBindLogDetailVO> pageVO = new Page<>();
        pageVO.setCurrentPage(page.getCurrentPage());
        pageVO.setPageSize(page.getPageSize());
        pageVO.setResult(voList);
        pageVO.setTotalCount(page.getTotalCount());
        pageVO.setTotalPage(page.getTotalPage());
        PageResult2 pageResult2 = PageUtil.getPageInfo(pageVO);
        return resultResponse(HaoBanErrCode.ERR_1, pageResult2);
    }

    //门店记录列表
    @RequestMapping("store-apply-list")
    public HaobanResponse storeApplyList(String storeId, BasePageInfo pageInfo, Integer auditType,
                                         Integer auditStatus, Integer manageFlag, String clerkId, String enterpriseId , String wxEnterpriseId) {
        List<String> storeIds = new ArrayList<>();
        if (manageFlag != null && manageFlag == 1) {
            List<String> roleStoreIds = staffApiService.getHaoBanStoreIdsRolesByClerkId(clerkId, wxEnterpriseId);
            storeIds.addAll(roleStoreIds);
        } else {
            storeIds.add(storeId);
        }
        if (CollectionUtils.isEmpty(storeIds)) {
            return resultResponse(HaoBanErrCode.ERR_10009);
        }
        if (storeIds.contains("-1")) {
            storeIds = null;
        }
        Page<AuditDTO> page = auditApiService.pageStoreListByParams(storeIds, pageInfo, auditType, auditStatus, wxEnterpriseId, enterpriseId);
        List<AuditDTO> list = page.getResult();
        List<AuditVO> voList = new ArrayList<AuditVO>();
        for (AuditDTO auditDTO : list) {
            AuditVO vo = EntityUtil.changeEntityByJSON(AuditVO.class, auditDTO);
            String clerkCode = "";
            String staffName = "";
            String oldValue = auditDTO.getOldValue();
            JSONObject json = JSON.parseObject(oldValue);
            clerkCode = json.getString("clerkCode");
            staffName = json.getString("staffName");
            String applyClerkId = json.getString("clerkId");
            String headPic = json.get("headPic") == null ? "" : json.get("headPic").toString();
            if (auditDTO.getAuditType() == 3) {
                vo.setCommitReason("添加导购账号：(" + clerkCode + ")");
            } else if (auditDTO.getAuditType() == 4) {
                vo.setCommitReason("删除导购账号：(" + clerkCode + ")");
            } else if (auditDTO.getAuditType() == 5) {
                vo.setCommitReason("解除绑定：(" + clerkCode + ")");
            } else {
                String commitReason = "绑定申请{" + staffName + "}绑定登录导购code " + clerkCode;
                ClerkDTO clerkDTO = clerkService.getClerkByClerkId(applyClerkId);
                if (clerkDTO != null) {
                    if (clerkDTO.getClerkType() == 2) {
                        commitReason = "绑定申请{" + staffName + "}绑定登录区经code " + clerkCode;
                    }
                }
                vo.setCommitReason(commitReason);
            }
            vo.setCommitName(auditDTO.getCommitStaffName());
            vo.setFailReason(auditDTO.getAuditReason());
            vo.setStaffName(auditDTO.getCommitName());
            vo.setClerkName(auditDTO.getCommitName());
            vo.setHeadPic(headPic);
            if (auditDTO.getAuditType() != 0) {
                vo.setUpdateTime(auditDTO.getUpdateTime());
            }
            voList.add(vo);
        }
        Page<AuditVO> pageVO = new Page<>();
        pageVO.setCurrentPage(page.getCurrentPage());
        pageVO.setPageSize(page.getPageSize());
        pageVO.setResult(voList);
        pageVO.setTotalCount(page.getTotalCount());
        pageVO.setTotalPage(page.getTotalPage());
        PageResult2 pageResult2 = PageUtil.getPageInfo(pageVO);
        return resultResponse(HaoBanErrCode.ERR_1, pageResult2);

    }

    //查单个
    @RequestMapping("get-store-record")
    public HaobanResponse getStoreRecord(String auditId) {
        if (auditId == null) {
            return resultResponse(HaoBanErrCode.ERR_2);
        }
        AuditDTO auditDTO = auditApiService.findById(auditId);
        AuditVO vo = EntityUtil.changeEntityByJSON(AuditVO.class, auditDTO);
        String clerkCode = "";
        String staffName = "";
        String oldValue = auditDTO.getOldValue();
        JSONObject json = JSON.parseObject(oldValue);
        clerkCode = json.getString("clerkCode");
        staffName = json.getString("staffName");
        String headPic = json.get("headPic") == null ? "" : json.get("headPic").toString();
        if (auditDTO.getAuditType() == 3) {
            vo.setCommitReason("添加导购账号：(" + clerkCode + ")");
        } else if (auditDTO.getAuditType() == 4) {
            vo.setCommitReason("删除导购账号：(" + clerkCode + ")");
        } else if (auditDTO.getAuditType() == 5) {
            vo.setCommitReason("解除绑定：(" + clerkCode + ")");
        } else {
            vo.setCommitReason("绑定申请{" + staffName + "}绑定登录导购code " + clerkCode);
        }
        vo.setHeadPic(headPic);
        vo.setCommitName(auditDTO.getCommitStaffName());
        vo.setFailReason(auditDTO.getAuditReason());
        vo.setStaffName(auditDTO.getCommitName());
        vo.setClerkName(auditDTO.getCommitName());
        if (auditDTO.getAuditType() != 0) {
            vo.setUpdateTime(auditDTO.getUpdateTime());
        }
        return resultResponse(HaoBanErrCode.ERR_1, vo);
    }

    //审核，1同意，2拒绝，3取消审核
    @HttpLimit
    @RequestMapping("clerk-audit")
    public HaobanResponse clerkAudit(String auditId, String auditReason, Integer auditStatus, String wxEnterpriseId, String staffId) {
        if (StringUtils.isAnyBlank(auditId, wxEnterpriseId)) {
            return resultResponse(HaoBanErrCode.ERR_2);
        }

        if (auditStatus == null) {
            return resultResponse(HaoBanErrCode.ERR_2);
        }
        String key = "audit-" + auditId;
        RedisUtil.lock(key, 10L);

        AuditDTO audit = auditApiService.findById(auditId);
        if (audit == null || audit.getAuditStatus() != 0) {
            RedisUtil.unlock(key);
            return resultResponse(HaoBanErrCode.ERR_10017);
        }
        StaffDTO staff = staffApiService.selectById(staffId);
        if (staff != null) {
            audit.setAuditName(staff.getStaffName());
        }

        String oldValue = audit.getOldValue();
        JSONObject json = JSON.parseObject(oldValue);
        String clerkCode = json.get("clerkCode") == null ? "" : json.get("clerkCode").toString();
        String enterpriseId = audit.getEnterpriseId();
        String clerkId = json.getString("clerkId") == null ? "" : json.get("clerkId").toString();
        String clerkName = json.get("clerkName") == null ? "" : json.get("clerkName").toString();
        Integer sex = json.getInteger("sex") == null ? 0 : json.getInteger("sex");
        String phoneNumber = json.getString("phoneNumber") == null ? "" : json.get("phoneNumber").toString();
        String nationCode = json.getString("nationCode") == null ? "" : json.get("nationCode").toString();
        String auditStaffId = json.getString("staffId") == null ? "" : json.get("staffId").toString();

        String storeId = audit.getCommitStoreId();
        if (auditStatus == 1) {
            //审核同意
            if (audit.getAuditType() == AuditType.CLERK_BIND.getCode()) {
                //导购绑定
                StaffClerkRelationDTO staffClerkRelation = staffClerkRelationApiService.getByCodeAndEnterpriseId(clerkCode, enterpriseId);
                StaffClerkRelationDTO have = staffClerkRelationApiService.getOneByStoreIdAndStaffId(storeId, auditStaffId);
                ClerkDTO clerkDTO = clerkService.getClerkByClerkId(clerkId);
                if (have != null) {
                    audit.setAuditStatus(5);
                    String reason = "该成员在该门店下已经绑定过一个导购了";
                    if (clerkDTO != null) {
                        if (clerkDTO.getClerkType() == 2) {
                            reason = "该成员在该商户下已经绑定过一个区经了";
                        }
                    }
                    audit.setAuditReason(reason);
                } else {
                    if (clerkDTO == null) {
                        audit.setAuditStatus(5);
                        audit.setAuditReason("gic已删除该导购");
                    } else {
                        if (staffClerkRelation == null) {
                            staffClerkRelation = new StaffClerkRelationDTO();
                        }
                        staffClerkRelation.setEnterpriseId(enterpriseId);
                        staffClerkRelation.setClerkCode(clerkCode);
                        staffClerkRelation.setClerkId(clerkId);
                        staffClerkRelation.setStoreId(storeId);
                        staffClerkRelation.setWxEnterpriseId(wxEnterpriseId);
                        staffClerkRelation.setStaffId(auditStaffId);
                        ServiceResponse serviceResponse = staffClerkRelationApiService.wxBindStaffClerk(staffClerkRelation, staffId, ChannelCodeEnum.AUDIT_BIND.getCode());
                        if (!serviceResponse.isSuccess()) {
                            return resultResponse(HaoBanErrCode.ERR_DEFINE, serviceResponse.getMessage());
                        }
                        audit.setAuditStatus(1);

                        //发送消息
                        staffDepartmentRelatedApiService.sendBindAuditMessage(auditId, auditStaffId, clerkId, "", false);
                    }
                }
            }
            if (audit.getAuditType() == AuditType.CLERK_ADD.getCode()) {
                //导购新增
                boolean flag = syncHaobanToGicApiService.syncClerkToGicClerkAdd(storeId, clerkCode, sex, clerkName, phoneNumber, nationCode, null);
                if (!flag) {
                    return resultResponse(HaoBanErrCode.ERR_10010);
                }
                audit.setAuditStatus(1);

                staffDepartmentRelatedApiService.sendClerkAdd(clerkName, clerkCode, storeId, auditStatus, auditReason);
            }
            if (audit.getAuditType() == AuditType.CLERK_DEL.getCode()) {
                //导购删除
                syncHaobanToGicApiService.delGicClerk(clerkId);
                audit.setAuditStatus(1);
                staffDepartmentRelatedApiService.sendClerkDel(clerkName, clerkCode, storeId, auditStatus, auditReason);
            }
        } else if (auditStatus == 2) {
            //审核拒绝
            audit.setAuditReason(auditReason);
            audit.setAuditStatus(2);
            //发送消息
            if (audit.getAuditType() == AuditType.CLERK_BIND.getCode()) {
                staffDepartmentRelatedApiService.sendBindAuditMessage(auditId, auditStaffId, clerkId, auditReason, true);
            } else if (audit.getAuditType() == AuditType.CLERK_ADD.getCode()) {
                staffDepartmentRelatedApiService.sendClerkAdd(clerkName, clerkCode, storeId, auditStatus, auditReason);
            } else if (audit.getAuditType() == AuditType.CLERK_DEL.getCode()) {
                staffDepartmentRelatedApiService.sendClerkDel(clerkName, clerkCode, storeId, auditStatus, auditReason);
            }

        } else if (auditStatus == 3) {
            //取消审核
            audit.setAuditStatus(3);
        }
        auditApiService.update(audit);
        RedisUtil.unlock(key);
        return resultResponse(HaoBanErrCode.ERR_1);
    }

    /**
     * 审核数量
     *
     * @param clerkId
     * @param enterpriseId
     * @return
     */
    @RequestMapping("get-audit-count")
    public RestResponse getAuditCount(String clerkId, String enterpriseId ,String wxEnterpriseId) {
        int count = this.auditApiService.getAuditCount(wxEnterpriseId, enterpriseId, clerkId);
        return RestResponse.successResult(count);
    }


}
