package com.ruoyi.app.mendian;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.ruoyi.app.utils.DateUtil;
import com.ruoyi.app.utils.ImageCompressUtils;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.PosStoreMapper;
import com.ruoyi.system.mapper.SysConfigMapper;
import com.ruoyi.system.service.*;
import com.ruoyi.system.utils.Auth;
import com.ruoyi.system.utils.JwtUtil;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * posstoreController
 *
 * @author ruoyi
 * @date 2023-05-14
 */
@RestController
@RequestMapping("/chanting/store")
public class PosStoreController extends BaseController
{
    @Autowired
    private IPosStoreService posStoreService;

    @Autowired
    private PosStoreMapper posStoreMapper;
    @Autowired
    private IPosCollectService posCollectService;
    @Autowired
    private IPosFenleiService posFenleiService;

    @Autowired
    private IInfoUserService infoUserService;
    @Autowired
    private IOperatingHoursService operatingHoursService;
    @Autowired
    private SysConfigMapper sysConfigMapper;





    /**
     * 根据评分查旬门店
     * @param longitude
     * @param latitude
     * @param page
     * @param juli
     * @param type
     * @return
     */
    @Anonymous
    @GetMapping("/getPfStore")
    public AjaxResult getPfStore(@RequestParam BigDecimal longitude,
                                    @RequestParam BigDecimal latitude,
                                    @RequestParam Integer page,
                                    @RequestParam Integer juli,
                                    @RequestParam Integer type)
    {
        if(type==0){
            List<PosStore> list = posStoreMapper.getPingfStore(longitude,latitude,(page-1)*10,juli);
            return success(list);
        }else if(type==1){
            List<PosStore> list = posStoreMapper.getReduStore(longitude,latitude,(page-1)*10,juli);
            return success(list);
        }else {
            List<PosStore> list = posStoreMapper.getNewStore(longitude,latitude,(page-1)*10,juli);
            return success(list);
        }
    }

    //删除我的门店
    @Anonymous
    @Auth
    @GetMapping("/delemendian")
    public AjaxResult delemendian(@RequestParam String id){
        QueryWrapper<PosFenlei> queryWrapper= new QueryWrapper<>();
        queryWrapper.eq("mendid",id);
        List<PosFenlei> list = posFenleiService.list(queryWrapper);
        if(list.size()>0){
            return error(MessageUtils.message("no.mendian.exist.classify.not.del"));
        }else {
            return toAjax(posStoreService.deletePosStoreById(Long.valueOf(id)));
        }
    }

    /**
     * H5端门店列表
     */
    @Anonymous
    @Auth
    @GetMapping("/storelistlist")
    public AjaxResult storelistlist(@RequestHeader String token,
                                    @RequestParam Integer page,
                                    @RequestParam Integer size)
    {
        JwtUtil jwtUtil = new JwtUtil();
        String id = jwtUtil.getusid(token);
        IPage<PosStore> stlist = new Page<>(page,size);
        QueryWrapper<PosStore> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",id);
        IPage<PosStore> list =  posStoreService.page(stlist,queryWrapper);
        if(!list.getRecords().isEmpty()){
            QueryWrapper<OperatingHours> wrapper = new QueryWrapper<>();
            wrapper.in("md_id",list.getRecords().stream().map(PosStore::getId).collect(Collectors.toList()));
            List<OperatingHours> hourslist = operatingHoursService.list(wrapper);
            list.getRecords().forEach(posStore -> {
                posStore.setBusinessHours(hourslist);
            });
        }

        return success(list);
    }
    //查询我的门店列表
    @Anonymous
    @Auth
    @GetMapping("/getmystorelist")
    public AjaxResult getmystorelist(@RequestHeader String token){
        JwtUtil jwtUtil = new JwtUtil();
        String id = jwtUtil.getusid(token);
        QueryWrapper<PosStore> queryWrapper= new QueryWrapper<>();
        queryWrapper.eq("user_id",id);
        List<PosStore> list = posStoreService.list(queryWrapper);
        return success(list);
    }

    //查询门店列表
    @Anonymous
    @GetMapping("/getstore")
    public AjaxResult getstore(@RequestHeader(defaultValue = "") String token,@RequestParam Integer id){
        if(!"".equals(token)){
            JwtUtil jwtUtil = new JwtUtil();
            String usid = jwtUtil.getusid(token);
            QueryWrapper<PosCollect> queryWrapper= new QueryWrapper<>();
            queryWrapper.eq("user_id",usid);
            queryWrapper.eq("md_id",id);
            List<PosCollect> list = posCollectService.list(queryWrapper);
            PosStore posStore = posStoreService.getById(id);
            JSONObject org = new JSONObject();
            org.put("id",posStore.getId());
            org.put("posName",posStore.getPosName());
            org.put("image",posStore.getImage());
            org.put("posPrice",posStore.getPosPrice());
            org.put("area",posStore.getArea());
            org.put("address",posStore.getAddress());
            org.put("longitude",posStore.getLongitude());
            org.put("latitude",posStore.getLatitude());
            org.put("briefIntroduction",posStore.getBriefIntroduction());
            org.put("type",posStore.getType());
            org.put("hygienePermit",posStore.getHygienePermit());
            org.put("hygieneLicence",posStore.getHygieneLicence());
            org.put("openBusiness",posStore.getOpenBusiness());
            org.put("windingUp",posStore.getWindingUp());
            org.put("sort",posStore.getSort());
            org.put("userId",posStore.getUserId());
            org.put("juli",posStore.getJuli());
            org.put("cretim",posStore.getCretim());
            org.put("zhitsj",posStore.getJuli());
            org.put("tgpaixv",posStore.getCretim());
            org.put("state",posStore.getState());
            org.put("serverType",posStore.getServerType());
            org.put("telephone",posStore.getTelephone());
            org.put("Collect", !list.isEmpty() ?1:0);
            org.put("logo",posStore.getLogo());
            org.put("isNightMarket",posStore.getIsNightMarket());
            org.put("nightMarketId",posStore.getNightMarketId());

            QueryWrapper<OperatingHours> wrapper = new QueryWrapper<>();
            wrapper.eq("md_id", posStore.getId());
            List<OperatingHours> hourslist = operatingHoursService.list(wrapper);
            DateUtil dateUtil = new DateUtil();
            Boolean dayang = false;
            //在营业时间范围内返回true
            for (int i = 0; i < hourslist.size(); i++) {
                Boolean sbsj = dateUtil.isLegalTime(hourslist.get(i).getStartTime(), hourslist.get(i).getEndTime());
                if (sbsj == true) {
                    dayang = true;
                }
            }
            //不在时间范围内标识为打烊
            if (dayang == false) {
                org.put("state",1);
            }
            org.put("businessHours", hourslist);
            return success(org);
        }else {
            PosStore posStore = posStoreService.getById(id);
            return success(posStore);
        }


    }
    //根据行业分类查询门店列表
    @Anonymous
    @GetMapping("/getstorelist")
    public AjaxResult getstorelist(@RequestParam BigDecimal longitude,
                                   @RequestParam BigDecimal latitude,
                                   @RequestParam Integer page,
                                   @RequestParam String area,
                                   @RequestParam Integer juli,
                                   @RequestParam(defaultValue = "") Integer sort)
    {
        if(sort==null){
            List<PosStore> list = posStoreMapper.getmdlist(longitude,latitude,(page-1)*20,"%"+area+"%",juli);

            return success(list);
        }else {
            List<PosStore> list = posStoreMapper.getdaidiq(longitude,latitude,(page-1)*20,"%"+area+"%",juli,sort);
            return success(list);
        }


    }
    //根据服务分类查询门店列表
    @Anonymous
    @GetMapping("/getserverlist")
    public AjaxResult getserverlist(@RequestParam BigDecimal longitude,
                                   @RequestParam BigDecimal latitude,
                                   @RequestParam Integer page,
                                   @RequestParam String area,
                                   @RequestParam Integer juli,
                                   @RequestParam(defaultValue = "") String serverType)
    {
        if(!"".equals(serverType)){
            List<PosStore> list = posStoreMapper.getserverlist(longitude,latitude,(page-1)*20,"%"+area+"%",juli,"%"+serverType+"%");
            return success(list);
        }else {
            List<PosStore> list = posStoreMapper.getmdlist(longitude,latitude,(page-1)*20,"%"+area+"%",juli);
            return success(list);
        }

    }
    //添加门店
    @Anonymous
    @PostMapping("/addmendian")
    @Transactional
    public AjaxResult addmendian(@RequestBody PosStore posStore)
    {
        Boolean org = posStoreService.saveOrUpdate(posStore);

        if(org){
            QueryWrapper<PosStore> wrapper = new QueryWrapper<>();
            wrapper.eq("pos_name",posStore.getPosName());
            wrapper.eq("user_id",posStore.getUserId());
            PosStore store = posStoreService.getOne(wrapper);

            if(posStore.getBusinessHours()!=null && posStore.getBusinessHours().size()>0){
                LambdaQueryWrapper<OperatingHours> query = new LambdaQueryWrapper<>();
                query.eq(OperatingHours::getMdId,Long.valueOf(store.getId()));
                operatingHoursService.remove( query);
                posStore.getBusinessHours().forEach(operatingHours -> {
                    operatingHours.setMdId(Long.valueOf(store.getId()));
                });
                operatingHoursService.saveBatch(posStore.getBusinessHours());
            }
            return success(MessageUtils.message("no.success"),store);
        }else {
            return error();
        }

    }
    /**
     * 查询posstore列表
     */
    @PreAuthorize("@ss.hasPermi('chanting:store:list')")
//    @Anonymous
    @GetMapping("/list")
    public TableDataInfo list(PosStore posStore)
    {
        startPage();
        List<PosStore> list = posStoreService.selectPosStoreList(posStore);
        for (PosStore store:list){
            InfoUser user = infoUserService.getById(store.getUserId());
            store.setUserName(user.getUserName());
        }
        return getDataTable(list);
    }

    /**
     * 导出posstore列表
     */
    @PreAuthorize("@ss.hasPermi('chanting:store:export')")
    @Log(title = "posstore", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PosStore posStore)
    {
        List<PosStore> list = posStoreService.selectPosStoreList(posStore);
        ExcelUtil<PosStore> util = new ExcelUtil<PosStore>(PosStore.class);
        util.exportExcel(response, list, MessageUtils.message("no.export.excel.posstore"));
    }

    /**
     * 获取posstore详细信息
     */
    @PreAuthorize("@ss.hasPermi('chanting:store:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(posStoreService.selectPosStoreById(id));
    }

    /**
     * 新增posstore
     */
    @PreAuthorize("@ss.hasPermi('chanting:store:add')")
    @Log(title = "posstore", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PosStore posStore)
    {
        return toAjax(posStoreService.insertPosStore(posStore));
    }

    /**
     * 修改posstore
     */
    @PreAuthorize("@ss.hasPermi('chanting:store:edit')")
    @Log(title = "posstore", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PosStore posStore)
    {
        return toAjax(posStoreService.updatePosStore(posStore));
    }
    /**
     * 修改posstore下架状态
     */
    @Anonymous
    @PutMapping("/changeOffShelf")
    public AjaxResult changeOffShelf(@RequestBody PosStore posStore)
    {
        Boolean res = posStoreService.saveOrUpdate(posStore);
        if (res){
            return success();
        }else {
            return error();
        }

    }
    /**
     * 删除posstore
     */
    @PreAuthorize("@ss.hasPermi('chanting:store:remove')")
    @Log(title = "posstore", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(posStoreService.deletePosStoreByIds(ids));
    }

    /**
     * 压缩图片店铺的商品图片
     */
    @Anonymous
    @GetMapping("/compressStoreImage")
    public AjaxResult compressStoreImage(@RequestParam String idsStr) {
        LambdaQueryWrapper<PosStore> queryWrapper = new LambdaQueryWrapper<>();

        List<Integer> ids= new ArrayList<>();
        if(!StringUtils.isEmpty(idsStr)){
            ids = Arrays.stream(idsStr.split(","))
                    .map(Integer::valueOf)
                    .collect(Collectors.toList());
        }
        queryWrapper.in(!ids.isEmpty(), PosStore::getId, ids);
        List<PosStore> list = posStoreService.list(queryWrapper);
        AtomicInteger count = new AtomicInteger();
        list.forEach(food -> {
            String compressImage = ImageCompressUtils.compressImageByWebPath(food.getImage());
            if (!compressImage.equals(food.getImage())) {
                food.setImage(compressImage);
                PosStore posStore = new PosStore();
                posStore.setId(food.getId());
                posStore.setImage(compressImage);
                posStoreService.saveOrUpdate(posStore);
                count.getAndIncrement();
                System.out.println("store成功压缩的图片数量:"+count.get());
                logger.info("store成功压缩的图片数量:"+count.get());
            }
        });
        return success("成功压缩的图片数量:"+count.get());
    }

}
