package com.fs.hisStore.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.fs.common.exception.CustomException;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.StringUtils;
import com.fs.his.param.FsStoreAuditParam;
import com.fs.his.utils.ConfigUtil;
import com.fs.his.utils.StoreMD5PasswordEncoder;
import com.fs.hisStore.domain.FsStoreProductCategoryScrm;
import com.fs.hisStore.domain.FsStoreProductScrm;
import com.fs.hisStore.domain.FsStoreScrm;
import com.fs.hisStore.mapper.FsStoreProductCategoryScrmMapper;
import com.fs.hisStore.mapper.FsStoreProductScrmMapper;
import com.fs.hisStore.mapper.FsStoreScrmMapper;
import com.fs.hisStore.service.IFsHisStoreAuditLogScrmService;
import com.fs.hisStore.service.IFsStoreScrmService;
import com.fs.hisStore.utils.StoreAuditLogUtil;
import com.fs.hisStore.vo.FsStoreRecommendListVO;
import com.fs.hisStore.vo.FsStoreScrmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 店铺管理Service业务层处理
 *
 * @author fs
 * @date 2023-06-15
 */
@Service
@Slf4j
public class FsStoreScrmServiceImpl implements IFsStoreScrmService
{
    @Autowired
    private FsStoreScrmMapper fsStoreMapper;

    @Autowired
    private StoreAuditLogUtil storeAuditLogUtil;

    @Autowired
    private FsStoreProductScrmMapper fsStoreProduct;
    @Autowired
    private ConfigUtil configUtil;


    /**
     * 查询店铺管理
     *
     * @param storeId 店铺管理主键
     * @return 店铺管理
     */
    @Override
    public FsStoreScrm selectFsStoreByStoreId(Long storeId)
    {
        return fsStoreMapper.selectFsStoreByStoreId(storeId);
    }

    @Override
    public List<FsStoreScrm> selectFsStoreByStoreIds(String[] storeId) {
        return fsStoreMapper.selectFsStoreByStoreIds(storeId);
    }

    /**
     * 查询店铺管理列表
     *
     * @param fsStore 店铺管理
     * @return 店铺管理
     */
    @Override
    public List<FsStoreScrm> selectFsStoreList(FsStoreScrm fsStore)
    {
        return fsStoreMapper.selectFsStoreList(fsStore);
    }

    /**
     * 新增店铺管理
     *
     * @param fsStore 店铺管理
     * @return 结果
     */
    @Override
    public Long insertFsStore(FsStoreScrm fsStore)
    {
        if (fsStore.getAccount()!=null){
            FsStoreScrm fs = fsStoreMapper.selectFsStoreByAccount(fsStore.getAccount());
            if (fs!=null){
                throw new CustomException("店铺账号重复");
            }
        }
        StoreMD5PasswordEncoder storeMD5PasswordEncoder = new StoreMD5PasswordEncoder();
        fsStore.setPassword(storeMD5PasswordEncoder.encode("XyzAbc~12"));
        fsStore.setCreateTime(DateUtils.getNowDate());
        fsStoreMapper.insertFsStore(fsStore);
        return fsStore.getStoreId();
    }

    /**
     * 修改店铺管理
     *
     * @param fsStore 店铺管理
     * @return 结果
     */
    @Override
    public int updateFsStore(FsStoreScrm fsStore)
    {
        fsStore.setUpdateTime(DateUtils.getNowDate());
        storeAuditLogUtil.addOperLog(fsStore.getStoreId());
        FsStoreScrm oldFsStore = fsStoreMapper.selectFsStoreByStoreId(fsStore.getStoreId());
        String isAudit = configUtil.generateConfigByKey("medicalMall.func.switch").getString("isAudit");
        try {
            if ("1".equals(isAudit)) {
                if (fsStore.getIsAudit() != null && 1 == fsStore.getIsAudit()) {
                    Map<String, Object> diff = getDiff(oldFsStore, fsStore);
                    Set<String> diff_columns = diff.keySet();
                    String passColumnStr = configUtil.generateConfigByKey("medicalMall.func.switch").getString("pass_columns");
                    if(StringUtils.isNotEmpty(passColumnStr)){
                        List<String> pass_columns = Arrays.asList(passColumnStr.split(","));
                        //判断diff_columns是否在pass_columns中，不是则将isAudit设置为0
                        for (String column : diff_columns) {
                            if (!pass_columns.contains(column)) {
                                fsStore.setIsAudit(0);
                                break;
                            }
                        }
                    }else{
                        fsStore.setIsAudit(0);
                    }
                }
            }
        } catch (IllegalAccessException e) {
            log.error("获取diff出错", e);
        }
        return fsStoreMapper.updateFsStore(fsStore);
    }

    public static Map<String, Object> getDiff(Object obj1, Object obj2) throws IllegalAccessException {
        Map<String, Object> diff = new HashMap<>();
        if (obj1 == null || obj2 == null || !obj1.getClass().equals(obj2.getClass())) {
            return diff;
        }

        Field[] fields = obj1.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            Object value1 = field.get(obj1);
            Object value2 = field.get(obj2);
            if (!Objects.equals(value1, value2)) {
                diff.put(field.getName(), new Object[]{value1, value2});
            }
        }
        return diff;
    }

    /**
     * 批量删除店铺管理
     *
     * @param storeIds 需要删除的店铺管理主键
     * @return 结果
     */
    @Override
    public int deleteFsStoreByStoreIds(Long[] storeIds)
    {
        storeAuditLogUtil.addBatchAuditArray(storeIds,null,null);
        return fsStoreMapper.deleteFsStoreByStoreIds(storeIds);
    }

    /**
     * 删除店铺管理信息
     *
     * @param storeId 店铺管理主键
     * @return 结果
     */
    @Override
    public int deleteFsStoreByStoreId(Long storeId)
    {
        return fsStoreMapper.deleteFsStoreByStoreId(storeId);
    }

    @Override
    @Transactional
    public int updateFsStoreAudit(FsStoreAuditParam fsStore) {

        fsStoreMapper.updateFsStoreAudit(fsStore.getStoreId(),fsStore.getIsAudit());
        //更新日志
        storeAuditLogUtil.addAudit(fsStore.getStoreId(),fsStore.getReason(),fsStore.getAttachImage());
        return 1;
    }

    @Override
    public int updateFsStoreLogo(FsStoreScrm fsStore) {


        return   fsStoreMapper.updateFsStore(fsStore);
    }

    @Override
    public int updateEditData(FsStoreScrm fsStore) {
        return fsStoreMapper.updateFsStore(fsStore);
    }

    @Override
    public List<FsStoreScrm> selectFsStoreListByDoctorId(Long doctorId) {
        return fsStoreMapper.selectFsStoreListByDoctorId(doctorId);
    }

    @Override
    public int refreshFsStore(Long storeId) {
        FsStoreScrm fsStoreScrm = new FsStoreScrm();
        fsStoreScrm.setStoreId(storeId);
        StoreMD5PasswordEncoder storeMD5PasswordEncoder = new StoreMD5PasswordEncoder();
        fsStoreScrm.setPassword(storeMD5PasswordEncoder.encode("XyzAbc~12"));
        fsStoreScrm.setUpdateTime(DateUtils.getNowDate());
        storeAuditLogUtil.addOperLog(storeId);
        return fsStoreMapper.updateFsStore(fsStoreScrm);
    }

    @Override
    public List<FsStoreScrm> selectOverList() {
        return fsStoreMapper.selectOverList();
    }

    @Override
    public int batchUpdateStatusByIds(List<Long> ids, Integer status) {
        if (ids == null || ids.isEmpty()) {
            return 0;
        }
        return fsStoreMapper.batchUpdateStatusByIds(ids, status);
    }

    @Override
    public List<FsStoreRecommendListVO> storeRecommendList() {
        FsStoreScrm fsStoreScrm = new FsStoreScrm();
        fsStoreScrm.setStatus(1);//启用
        fsStoreScrm.setIsAudit(1);//审核通过
        //List<FsStoreScrm>  storeList =  fsStoreMapper.selectFsStoreList( fsStoreScrm);
//        List<FsStoreScrm>  storeList =  fsStoreMapper.selectFsStoreList(fsStoreScrm);
        List<FsStoreScrm>  storeList =  fsStoreMapper.selectFsStoreListByProduct(fsStoreScrm); //查询有商品的列表
        return storeList.stream().map(store -> {
            FsStoreProductScrm fsStoreProductScrm = new FsStoreProductScrm();
            fsStoreProductScrm.setStoreId(store.getStoreId());
            fsStoreProductScrm.setIsAudit("1");//审核通过
            fsStoreProductScrm.setIsGood(1);//推荐
            fsStoreProductScrm.setIsShow(1);//上架
            fsStoreProductScrm.setIsDel(0);
            List<FsStoreProductScrm> fsStoreProductScrms = fsStoreProduct.selectFsStoreProductList(fsStoreProductScrm);
            if (fsStoreProductScrms != null && !fsStoreProductScrms.isEmpty()) {
                return FsStoreRecommendListVO.builder().store(store).recommendProductList(fsStoreProductScrms).build();
            } else {
                return null;
            }
        }).collect(Collectors.toList());
    }

    @Override
    public List<FsStoreScrmVO> selectAllStore() {
        return fsStoreMapper.selectFsAllStoreList();
    }

}

