package com.ruixuan.isc.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kuaishou.merchant.open.api.KsMerchantApiException;
import com.ruixuan.bytedance.service.IBytedanceService;
import com.ruixuan.common.annotation.Log;
import com.ruixuan.common.core.controller.BaseController;
import com.ruixuan.common.core.domain.AjaxResult;
import com.ruixuan.common.core.page.TableDataInfo;
import com.ruixuan.common.enums.BusinessType;
import com.ruixuan.common.utils.Check;
import com.ruixuan.isc.entity.KuaishouAccessToken;
import com.ruixuan.isc.entity.KuaishouItemList;
import com.ruixuan.isc.service.IAccessTokenService;
import com.ruixuan.isc.service.IKuaishouItemListService;
import com.ruixuan.isc.service.impl.CityMap;
import com.ruixuan.system.service.ISysDeptService;
import com.ruixuan.system.service.ISysRoleService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


/**
 * 【请填写功能名称】Controller
 *
 * @author ruoyi
 * @date 2023-02-03
 */
@RestController
@RequestMapping("/item")
public class KuaishouItemListController extends BaseController {
    @Autowired
    private IKuaishouItemListService kuaishouItemListService;
    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private IAccessTokenService accessTokenService;
    @Autowired
    private IBytedanceService bytedanceService;


    @GetMapping("/bytedanceToken")
    @ApiOperation(value = "商品列表")
    public void bytedanceToken() {
        accessTokenService.refreshByteDanceAccessToken();
    }


    @GetMapping("/accessToken")
    @ApiOperation(value = "商品列表")
    public void accessToken() {
        accessTokenService.refreshAccessToken();
    }

    @GetMapping("/getRegimental")
    @ApiOperation(value = "团长信息")
    public JSONObject getRegimental() {
        JSONObject returnJson = new JSONObject();
        try {
            List<JSONObject> list = kuaishouItemListService.getRegimental();
            returnJson.put("code", 0);
            returnJson.put("message", "success");
            returnJson.put("data", list);
        } catch (Exception e) {
            e.printStackTrace();
            returnJson.put("code", -1);
            returnJson.put("message", e.getMessage());
        }
        return returnJson;
    }


    @GetMapping("/getActivityIds")
    @ApiOperation(value = "活动列表")
    public JSONObject getActivityIds(Long userId) {
        JSONObject returnJson = new JSONObject();
        try {
            if (Check.isNull(userId)) {
                throw new Exception("请传入用户ID");
            }
            List<Long> activityIds = kuaishouItemListService.getActivityIds(userId);
            returnJson.put("code", 0);
            returnJson.put("message", "success");
            returnJson.put("data", activityIds);
        } catch (Exception e) {
            e.printStackTrace();
            returnJson.put("code", -1);
            returnJson.put("message", e.getMessage());
        }
        return returnJson;
    }


    @GetMapping("/getItemPreview")
    @ApiOperation(value = "商品详情预览")
    public JSONObject getItemPreview(
            @ApiParam("活动ID") @RequestParam(value = "activityId", required = false) Long activityId,
            @ApiParam("商品ID") @RequestParam(value = "itemId", required = false) Long itemId,
            @ApiParam("团长ID") @RequestParam(value = "regId", required = false) Long regId,
            @ApiParam("媒体ID") @RequestParam(value = "mediaId", required = false) Long mediaId,
            @ApiParam("类型") @RequestParam(value = "byteDanceItemType", required = false) Integer byteDanceItemType

    ) {
        JSONObject returnJson = new JSONObject();
        try {
            if (Check.isNull(itemId)) {
                throw new Exception("请传入商品ID");
            }
          /*  if (Check.isNull(regId)) {
                throw new Exception("请选择所属团");
            }*/
           /* if (Check.isNull(activityId)) {
                throw new Exception("请输入活动ID");
            }*/
            if (Check.isNull(mediaId)) {
                throw new Exception("请选择媒体");
            }
            if (mediaId == 2) {
                KuaishouAccessToken accessToken = accessTokenService.getAccessToken(regId);
                if (Check.isNull(accessToken)) {
                    throw new Exception("获取token授权信息为空");
                }
                returnJson = kuaishouItemListService.getItemDetail(regId, activityId, itemId, accessToken);
            } else if (mediaId == 1) {
                if(byteDanceItemType == 1 ){ // 常规
                    returnJson = bytedanceService.addBytedanceColonelActivityProduct(activityId, itemId);
                }  else if(byteDanceItemType == 2 ){ // 托管
                    returnJson = bytedanceService.trusteeship(activityId, itemId);
                }


            }

        } catch (Exception e) {
            e.printStackTrace();
            returnJson.put("code", 500);
            returnJson.put("message", e.getMessage());
        }
        return returnJson;
    }


    @GetMapping("/list")
    @ApiOperation(value = "商品列表")
    public TableDataInfo orderList(
            @ApiParam("用户id") @RequestParam(value = "userId", required = false) Long userId,
            @ApiParam("审核状态") @RequestParam(value = "examineStatus", required = false) Long examineStatus,
            @ApiParam("商品ID") @RequestParam(value = "itemId", required = false) Long itemId,
            @ApiParam("商品名称") @RequestParam(value = "itemTitle", required = false) String itemTitle,
            @ApiParam("品类ID") @RequestParam(value = "categoryId", required = false) Long categoryId,
            @ApiParam("品类ID") @RequestParam(value = "mediaId", required = false) Integer mediaId
    ) {
        TableDataInfo dataInfo = new TableDataInfo();
        try {
            Map<String, Object> requestMap = new HashMap<>();
            if (!Check.isNull(userId)) {
                String roleKey = sysRoleService.getRoleBYUserId(userId);
                if (roleKey.equals("courtship")) {
                    requestMap.put("userId", userId);
                } else if (roleKey.equals("courtshipManager")) {
                    Long deptId = sysDeptService.getDeptIdByUserId(userId);
                    if (Check.isNull(deptId)) {
                        throw new Exception("此用户未获取相关部门");
                    }
                    List<Long> userIds = sysDeptService.getDeptUserListByDeptId(deptId);
                    requestMap.put("userIds", userIds);
                }
            }
            if (!Check.isNull(examineStatus)) {
                requestMap.put("examineStatus", examineStatus);
            }
            if (!Check.isNull(itemId)) {
                requestMap.put("itemId", itemId);
            }
            if (!Check.isNull(itemTitle)) {
                requestMap.put("itemTitle", itemTitle);
            }
            if (!Check.isNull(categoryId)) {
                requestMap.put("categoryId", categoryId);
            }
            if (!Check.isNull(mediaId)) {
                requestMap.put("mediaId", mediaId);
            }

            startPage();
            List<KuaishouItemList> list = kuaishouItemListService.getItemList(requestMap);
            dataInfo = getDataTable(list);
        } catch (Exception e) {
            e.printStackTrace();
            dataInfo.setMsg(e.getMessage());
            dataInfo.setCode(-1);
        }
        return dataInfo;
    }


    @GetMapping("/checkItem")
    @ApiOperation(value = "检查此商品是否被绑定")
    @PostMapping
    public JSONObject checkItem(Long itemId) {
        JSONObject returnJson = new JSONObject();
        try {
            if (Check.isNull(itemId)) {
                throw new Exception("请传入商品ID");
            }
            KuaishouItemList itemInfo = kuaishouItemListService.getItemInfoByItemId(itemId);
            if (Check.isNull(itemInfo)) {
                returnJson.put("code", 0);
                returnJson.put("message", "true");
            } else {
                returnJson.put("code", 1);
                returnJson.put("message", "此商品已被：" + itemInfo.getUserName() + "绑定！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            returnJson.put("code", 500);
            returnJson.put("message", e.getMessage());
        }
        return returnJson;
    }


    @PostMapping("/insertItem")
    @ApiOperation(value = "商品列表")
    public JSONObject insertItem(@RequestBody KuaishouItemList kuaishouItemList) {
        JSONObject returnJson = new JSONObject();
        try {
            Long itemId = kuaishouItemList.getItemId();
            if (Check.isNull(itemId)) {
                throw new Exception("请传入商品ID");
            }
            kuaishouItemListService.insertItem(kuaishouItemList);
            returnJson.put("code", 0);
            returnJson.put("message", "添加成功");

        } catch (Exception e) {
            e.printStackTrace();
            returnJson.put("code", -1);
            returnJson.put("message", e.getMessage());
        }
        return returnJson;

    }


    @DeleteMapping("/unbindingItem")
    public JSONObject unbindingItem(Long itemId) {
        JSONObject returnJson = new JSONObject();
        try {
            if (Check.isNull(itemId)) {
                throw new Exception("商品ID不能为空");
            }
            Integer count = kuaishouItemListService.getSampleCount(itemId);
            if (count > 0) {
                returnJson.put("code", 500);
                returnJson.put("message", "此商品有未完成的领样申请，暂时无法解绑");
                return returnJson;
            }
            kuaishouItemListService.removeById(itemId);
            returnJson.put("code", 0);
            returnJson.put("message", "解绑成功");
            return returnJson;
        } catch (Exception e) {
            returnJson.put("code", 500);
            returnJson.put("message", e.getMessage());
            return returnJson;
        }
    }


    /**
     * 修改
     */

    @Log(title = "修改", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody KuaishouItemList kuaishouItemList) {
        return toAjax(kuaishouItemListService.updateKuaishouItemList(kuaishouItemList));
    }


    @Log(title = "获取省份")
    @GetMapping("/getProvince")
    @ResponseBody
    public JSONArray getProvince() {
        return CityMap.getProvince();
    }


    @Log(title = "获取城市")
    @GetMapping("/getCity")
    @ResponseBody
    public String getCity(String province) {
        return CityMap.getCity(province);
    }

    /**
     * 删除
     */

    @Log(title = "删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/remove")
    public AjaxResult remove(@PathVariable Long[] itemIds) {
        return toAjax(kuaishouItemListService.deleteKuaishouItemListByItemIds(itemIds));
    }


    @GetMapping("/addCategoryId")
    public void addCategoryId() throws KsMerchantApiException {
        kuaishouItemListService.addCategoryId();
    }

    @GetMapping("/getCategoryIds")
    public List<JSONObject> getCategoryIds() {
        List<JSONObject> array = kuaishouItemListService.getCategoryIds();
        return array;
    }


    @GetMapping("/getItemDetailByItemId")
    public JSONObject getItemDetail(Long itemId) {
        JSONObject returnJson = new JSONObject();
        try {
            if (Check.isNull(itemId)) {
                throw new Exception("请输入商品ID");
            }
            KuaishouItemList json = kuaishouItemListService.getItemInfoByItemId(itemId);
            returnJson.put("code", 0);
            returnJson.put("message", "success");
            returnJson.put("itemJson", json);
            returnJson.put("judgeStatus", 1);
        } catch (Exception e) {

            returnJson.put("code", 500);
            returnJson.put("message", e.getMessage());
        }

        return returnJson;
    }


    @PostMapping("/batchItemProcess")
    @ResponseBody
    public JSONObject batchItemProcess(@RequestBody JSONObject requestJson) {
        JSONObject returnJson = new JSONObject();
        try {
            JSONArray itemIds = requestJson.getJSONArray("itemIds");
            if (Check.isNull(itemIds)) {
                throw new Exception("请传入需要审核的商品ID");
            }
            Integer status = requestJson.getInteger("status");
            if (Check.isNull(status)) {
                throw new Exception("请传入审核状态");
            }
            Long examineId = requestJson.getLong("examineId");
            if (Check.isNull(examineId)) {
                throw new Exception("请传入审核人ID");
            }
            String examineName = requestJson.getString("examineName");
            if (Check.isNull(examineName)) {
                throw new Exception("请传入审核人名称");
            }
            kuaishouItemListService.batchItemProcess(itemIds, status, examineId, examineName);
            returnJson.put("code", 0);
            returnJson.put("message", "批量审核通过");
        } catch (Exception e) {
            returnJson.put("code", 500);
            returnJson.put("message", e.getMessage());
        }
        return returnJson;
    }


    @GetMapping("/editRelateByItemId")
    public JSONObject editRelateByItemId(Long itemId, Long relateId) {
        JSONObject returnJson = new JSONObject();
        try {
            KuaishouItemList itemInfoByItemId = kuaishouItemListService.getItemInfoByItemId(itemId);
            if (Check.isNull(itemInfoByItemId)) {
                throw new Exception("该商品未绑定");
            }
            KuaishouItemList update = new KuaishouItemList();
            update.setItemId(itemId);
            update.setRelateId(relateId);
            int i = kuaishouItemListService.updateKuaishouItemList(update);
            if (i > 0) {
                returnJson.put("code", 0);
                returnJson.put("message", "修改成功");
            }
        } catch (Exception e) {
            returnJson.put("code", 500);
            returnJson.put("message", e.getMessage());
        }
        return returnJson;
    }


    @GetMapping("/removeRelateByItemId")
    public JSONObject removeRelateByItemId(Long itemId) {
        JSONObject returnJson = new JSONObject();
        try {
            KuaishouItemList itemInfoByItemId = kuaishouItemListService.getItemInfoByItemId(itemId);
            if (Check.isNull(itemInfoByItemId)) {
                throw new Exception("该商品未绑定");
            }
            KuaishouItemList update = new KuaishouItemList();
            update.setItemId(itemId);
            Long relateId = kuaishouItemListService.selectMaxRelateId();
            update.setRelateId(relateId + 1);
            int i = kuaishouItemListService.updateKuaishouItemList(update);
            if (i > 0) {
                returnJson.put("code", 0);
                returnJson.put("message", "修改成功");
            }
        } catch (Exception e) {
            returnJson.put("code", 500);
            returnJson.put("message", e.getMessage());
        }
        return returnJson;
    }


    @GetMapping("/editRuleIdByItemId")
    public JSONObject editRuleIdByItemId(Long itemId, Long ruleId) {
        JSONObject returnJson = new JSONObject();
        try {
            KuaishouItemList itemInfoByItemId = kuaishouItemListService.getItemInfoByItemId(itemId);
            if (Check.isNull(itemInfoByItemId)) {
                throw new Exception("该商品未绑定");
            }
            KuaishouItemList update = new KuaishouItemList();
            update.setItemId(itemId);
            update.setRuleId(ruleId);
            int i = kuaishouItemListService.updateKuaishouItemList(update);
            if (i > 0) {
                returnJson.put("code", 0);
                returnJson.put("message", "修改成功");
            }
        } catch (Exception e) {
            returnJson.put("code", 500);
            returnJson.put("message", e.getMessage());
        }
        return returnJson;
    }


    @GetMapping("/getListByRelateId")
    public JSONObject getListByRelateId(Long relateId) {
        JSONObject returnJson = new JSONObject();
        try {
            List<JSONObject> list = kuaishouItemListService.getListByRelateId(relateId);
            returnJson.put("code", 0);
            returnJson.put("data", list);
            returnJson.put("message", "修改成功");

        } catch (Exception e) {
            returnJson.put("code", 500);
            returnJson.put("message", e.getMessage());
        }
        return returnJson;
    }


}

