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

import com.alibaba.fastjson.JSONObject;
import com.gic.api.base.commons.Page;
import com.gic.clerk.api.dto.ClerkDTO;
import com.gic.clerk.api.service.ClerkService;
import com.gic.enterprise.api.dto.StoreDTO;
import com.gic.enterprise.api.service.StoreService;
import com.gic.haoban.base.api.common.BasePageInfo;
import com.gic.haoban.base.api.common.pojo.dto.WebLoginDTO;
import com.gic.haoban.common.anno.HttpLimit;
import com.gic.haoban.common.utils.AuthWebRequestUtil;
import com.gic.haoban.common.utils.HaobanResponse;
import com.gic.haoban.common.utils.UuidUtil;
import com.gic.haoban.manage.api.dto.*;
import com.gic.haoban.manage.api.enums.StoreFieldEnum;
import com.gic.haoban.manage.api.service.AuditApiService;
import com.gic.haoban.manage.api.service.AuditSettingApiService;
import com.gic.haoban.manage.api.service.StaffApiService;
import com.gic.haoban.manage.web.errCode.HaoBanErrCode;
import com.gic.haoban.manage.web.vo.BatchApproveVO;
import com.gic.redis.data.util.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/audit")
public class AuditController extends WebBaseController {
    private static final Logger log = LogManager.getLogger(AuditController.class);

    @Autowired
    private AuditSettingApiService auditSettingApiService;
    @Autowired
    private AuditApiService auditApiService;
    @Autowired
    private StaffApiService staffApiService;
    @Autowired
    private StoreService storeService;
    @Autowired
    private ClerkService clerkService;

    //设置保存
    @HttpLimit
    @RequestMapping("open-or-close")
    public HaobanResponse openOrClose(String wxEnterpriseId, Integer auditFlag, int clerkChangeFlag) {
        if (StringUtils.isAnyBlank(wxEnterpriseId)) {
            return resultResponse(HaoBanErrCode.ERR_2);
        }
        if (auditFlag == null) {
            return resultResponse(HaoBanErrCode.ERR_2);
        }
        auditSettingApiService.saveSetting(wxEnterpriseId, auditFlag, clerkChangeFlag);
        return resultResponse(HaoBanErrCode.ERR_1);
    }

    //设置查看
    @RequestMapping("find-setting")
    public HaobanResponse findSetting(String wxEnterpriseId) {
        if (StringUtils.isAnyBlank(wxEnterpriseId)) {
            return resultResponse(HaoBanErrCode.ERR_2);
        }
        AuditSettingDTO auditSettingDTO = auditSettingApiService.findSettingByWxEnterpriseId(wxEnterpriseId);
        if (auditSettingDTO == null) {
            auditSettingDTO = new AuditSettingDTO();
            auditSettingDTO.setAuditFlag(1);
            auditSettingDTO.setClerkChangeFlag(1);
        }
        return resultResponse(HaoBanErrCode.ERR_1, auditSettingDTO);
    }

    //分页查找
    @RequestMapping("find-page")
    public HaobanResponse findPage(String search, BasePageInfo pageInfo, Integer auditType, Integer auditStatus, Integer auditFlag) {
        if (auditFlag == null) {
            return resultResponse(HaoBanErrCode.ERR_2);
        }
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        String enterpriseId = loginUser.getEnterpriseId();
        String clerkId = AuthWebRequestUtil.getLoginUser().getClerkId();
        String wxEnterpriseId = loginUser.getWxEnterpriseId();
        Page<AuditDTO> page = auditApiService.page(auditType, search, wxEnterpriseId, enterpriseId, auditStatus, auditFlag, pageInfo, clerkId);
        List<AuditDTO> list = page.getResult();
        List<String> storeIds = list.stream().map(s -> s.getCommitStoreId()).collect(Collectors.toList());
        String[] array = storeIds.toArray(new String[storeIds.size()]);
        List<StoreDTO> stores = storeService.getStores(array);
        Map<String, StoreDTO> map = com.gic.commons.util.CollectionUtil.toMap(stores, "storeId");
        for (AuditDTO dto : list) {
            if (dto.getAuditType() != null && dto.getAuditType() == 1) {
                String t = dto.getChangeField();
                String detail = "";
                if (StoreFieldEnum.STORE_NAME.getValue().equals(t)) {
                    detail = "将" + "门店名称" + "\"" + dto.getOldValue() + "\"" + "修改为" + "\"" + dto.getNewValue() + "\"";
                } else if (StoreFieldEnum.STORE_AREA.getValue().equals(t)) {
                    detail = "将" + "门店面积" + "\"" + dto.getOldValue() + "\"" + "修改为" + "\"" + dto.getNewValue() + "\"";
                } else if (StoreFieldEnum.CONACTS_PHONE.getValue().equals(t)) {
                    detail = "将" + "联系电话" + "\"" + dto.getOldValue() + "\"" + "修改为" + "\"" + dto.getNewValue() + "\"";
                } else if (StoreFieldEnum.BUSINESS_TIME_STRING.getValue().equals(t)) {
                    detail = "将" + "营业时间" + "\"" + dto.getOldValue() + "\"" + "修改为" + "\"" + dto.getNewValue() + "\"";
                } else if (StoreFieldEnum.STORE_ADDRESS.getValue().equals(t)) {
                    String oldValue = dto.getOldValue();
                    String newValue = dto.getNewValue();
                    JSONObject oldJSONObject = JSONObject.parseObject(oldValue);
                    String oldAddress = oldJSONObject.get("storeAddress").toString();
                    JSONObject newJSONObject = JSONObject.parseObject(newValue);
                    String newAddress = newJSONObject.get("storeAddress").toString();
                    detail = "将" + "门店地址" + "\"" + oldAddress + "\"" + "修改为" + "\"" + newAddress + "\"";
                } else if (StoreFieldEnum.STORE_IMAG.getValue().equals(t)) {
                    detail = "门店图片变更";
                }
                dto.setDetail(detail);
            } else if (dto.getAuditType() != null && dto.getAuditType() == 3) {
                //新增导购
                String oldValue = dto.getOldValue();
                AuditStaffDTO auditStaffDTO = JSONObject.parseObject(oldValue, AuditStaffDTO.class);
                String detail = "新增导购：" + auditStaffDTO.getClerkName() + "(" + auditStaffDTO.getClerkCode() + ")";
                dto.setDetail(detail);
            } else if (dto.getAuditType() != null && dto.getAuditType() == 4) {
                //删除导购
                String oldValue = dto.getOldValue();
                AuditStaffDTO auditStaffDTO = JSONObject.parseObject(oldValue, AuditStaffDTO.class);
                String detail = "删除导购：" + auditStaffDTO.getClerkName() + "(" + auditStaffDTO.getClerkCode() + ")";
                dto.setDetail(detail);
            } else if (dto.getAuditType() != null && dto.getAuditType() == 2) {
                //门店导购绑定
                String oldValue = dto.getOldValue();
                AuditStaffDTO oldAuditStaffDTO = JSONObject.parseObject(oldValue, AuditStaffDTO.class);
                String staffName = oldAuditStaffDTO.getStaffName();
                String clerkCode = oldAuditStaffDTO.getClerkCode();
                ClerkDTO clerkDTO = clerkService.getClerkByClerkId(oldAuditStaffDTO.getClerkId());
                String detail = staffName + "申请关联导购code:" + clerkCode;
                if (clerkDTO != null) {
                    Integer clerkType = clerkDTO.getClerkType();
                    if (clerkType == 2) {
                        detail = staffName + "申请关联区经code:" + clerkCode;
                    }
                }
                dto.setDetail(detail);
            } else if (dto.getAuditType() != null && dto.getAuditType() == 5) {
                //门店导购解绑
                String oldValue = dto.getOldValue();
                AuditStaffDTO oldAuditStaffDTO = JSONObject.parseObject(oldValue, AuditStaffDTO.class);
                String staffName = oldAuditStaffDTO.getStaffName();
                String clerkCode = oldAuditStaffDTO.getClerkCode();
                String detail = staffName + "申请解绑导购code：" + clerkCode;
                dto.setDetail(detail);
            }
            String storeName = map.get(dto.getCommitStoreId()) == null ? "" : map.get(dto.getCommitStoreId()).getStoreName();
            dto.setCommitStoreName(storeName);
        }
        page.setResult(list);
        return resultResponse(HaoBanErrCode.ERR_1, page);
    }

    //获取详情
    @RequestMapping("get-staff-detail")
    public HaobanResponse getStaffDetail(String staffId) {
        if (StringUtils.isAnyBlank(staffId)) {
            return resultResponse(HaoBanErrCode.ERR_2);
        }
        StaffDTO staffDTO = staffApiService.selectById(staffId);
        return resultResponse(HaoBanErrCode.ERR_1, staffDTO);
    }

    //批量同意
    @HttpLimit
    @RequestMapping("batch-approve")
    public HaobanResponse batchApprove(String auditIds) {
        if (StringUtils.isAnyBlank(auditIds)) {
            return resultResponse(HaoBanErrCode.ERR_2);
        }
        WebLoginDTO login = AuthWebRequestUtil.getLoginUser();
        String staffId = login.getClerkId();
        String staffName = login.getClerkName();
        String[] s = auditIds.split(",");
        int successCount = 0;
        int failCount = 0;
        String batchId = UuidUtil.randomUUID();
        for (String auditId : s) {
            String result = auditApiService.audit(batchId, auditId, staffName, staffId);
            if (StringUtils.isEmpty(result)) {
                successCount = successCount + 1;
            } else {
                failCount = failCount + 1;
            }
        }
        BatchApproveVO vo = new BatchApproveVO();
        vo.setSuccessCount(successCount);
        vo.setFailCount(failCount);
        vo.setBatchId(batchId);
        return resultResponse(HaoBanErrCode.ERR_1, vo);
    }

    //审核拒绝
    @HttpLimit
    @RequestMapping("refuse")
    public HaobanResponse refuse(String auditId, String auditReason) {
        if (StringUtils.isAnyBlank(auditId, auditReason)) {
            return resultResponse(HaoBanErrCode.ERR_2);
        }
        WebLoginDTO login = AuthWebRequestUtil.getLoginUser();
        String staffId = login.getClerkId();
        String staffName = login.getClerkName();
        auditApiService.refuse(auditId, auditReason, staffId, staffName);
        return resultResponse(HaoBanErrCode.ERR_1);
    }

    //审核同意
    @HttpLimit
    @RequestMapping("audit")
    public HaobanResponse audit(String auditId, String auditName) {
        WebLoginDTO login = AuthWebRequestUtil.getLoginUser();
        String staffId = login.getClerkId();
        String staffName = login.getClerkName();
        if (StringUtils.isAnyBlank(auditId)) {
            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);
        }
        String result = auditApiService.audit("", auditId, staffName, staffId);
        RedisUtil.unlock(key);
        if (StringUtils.isEmpty(result)) {
            return resultResponse(HaoBanErrCode.ERR_1);
        } else {
            HaoBanErrCode errCode = HaoBanErrCode.ERR_DEFINE;
            errCode.setMsg(result);
            return resultResponse(errCode);
        }
    }

    //批量审核详情
    @HttpLimit
    @RequestMapping("audit-detail-list")
    public HaobanResponse auditDetailList(String batchId) {
        if (StringUtils.isAnyBlank(batchId)) {
            return resultResponse(HaoBanErrCode.ERR_2);
        }
        List<BatchAuditLogDTO> list = auditApiService.listBatchLog(batchId);
        return resultResponse(HaoBanErrCode.ERR_1, list);
    }

    @RequestMapping("get-audit-count")
    public HaobanResponse getAuditCount() {
        WebLoginDTO login = AuthWebRequestUtil.getLoginUser();
        String eid = login.getEnterpriseId();
        String clerkId = login.getClerkId();
        String wxEnterpriseId = login.getWxEnterpriseId();
        int count = this.auditApiService.getAuditCount(wxEnterpriseId, eid, clerkId);
        return this.success(count);
    }
}
