package org.jeecg.modules.okki.site.controller;

import com.lark.oapi.service.contact.v3.model.P1UserChangedV3;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHeaders;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.FastJsonUtil;
import org.jeecg.modules.okki.site.dto.FeiShuRecordSheetDto;
import org.jeecg.modules.okki.site.dto.FeiShuSeoTeamRecordSheetDto;
import org.jeecg.modules.okki.site.dto.WeChatMsgDto;
import org.jeecg.modules.okki.site.param.ChangeSiteStatusParam;
import org.jeecg.modules.okki.site.param.OkkiSiteParam;
import org.jeecg.modules.okki.site.service.IFeiShuMsgService;
import org.jeecg.modules.okki.site.service.IFeiShuSeoTeamSheetService;
import org.jeecg.modules.okki.site.service.IFeiShuSheetService;
import org.jeecg.modules.okki.site.service.IOkkiSiteService;
import org.jeecg.modules.okki.wechatgroup.entity.OkkiShopWechatGroupMsg;
import org.jeecg.modules.okki.wechatgroup.service.IOkkiShopWechatGroupMsgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @Description: 站点
 * @Author: Jack
 * @Date: 2024-04-29
 * @Version: V1.0
 */
@RestController
@Slf4j
@RequestMapping("/website")
public class ShopApiController {

    @Autowired
    private IOkkiSiteService okkiSiteService;

    @Autowired
    private IFeiShuSheetService feiShuSheetService;

    @Autowired
    private IFeiShuSeoTeamSheetService feiShuSeoTeamSheetService;

    @Autowired
    private IFeiShuMsgService feiShuMsgService;

    @Autowired
    private IOkkiShopWechatGroupMsgService okkiShopWechatGroupMsgService;

    @Value("${file.jsonPath}")
    private String fileJsonPath;

    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody OkkiSiteParam okkiSiteParam, @RequestHeader(HttpHeaders.AUTHORIZATION) String authorization) {
        log.info("请求参数 param" + okkiSiteParam.toString() + "authorization" + authorization);
        String Authorization = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImRlYW4iLCJleHAiOjE3MTQ0NjU5Njl9.QdCBYR8mioXcKGi1n5RdMQ5RbJHCSGbE8dkdwYuOXh4";
        if (!authorization.equals(Authorization)) {
            return Result.error("sign 验证不通过");
        }
        // 如果站点id已存在 则提示信息
        boolean result = okkiSiteService.insertSite(okkiSiteParam);
        log.info("请求成功，返回结果" + result);
        if (result) {
            return Result.OK("添加成功！");
        } else {
            return Result.error("添加失败！");
        }
    }

    @PostMapping(value = "/edit")
    public Result<String> edit(@RequestBody OkkiSiteParam okkiSiteParam, @RequestHeader(HttpHeaders.AUTHORIZATION) String authorization) {
        log.info("请求参数 param" + okkiSiteParam.toString() + "authorization" + authorization);
        String Authorization = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImRlYW4iLCJleHAiOjE3MTQ0NjU5Njl9.QdCBYR8mioXcKGi1n5RdMQ5RbJHCSGbE8dkdwYuOXh4";
        if (!authorization.equals(Authorization)) {
            return Result.error("sign 验证不通过");
        }
        boolean result = okkiSiteService.updateBySiteId(okkiSiteParam);
        log.info("请求成功，返回结果" + result);
        if (result) {
            return Result.OK("编辑成功！");
        } else {
            return Result.error("编辑失败！");
        }
    }

    @PostMapping(value = "/changeStatus")
    public Result<String> changeStatus(@RequestBody ChangeSiteStatusParam param, @RequestHeader(HttpHeaders.AUTHORIZATION) String authorization) {
        log.info("请求参数 param" + param.toString() + ",authorization" + authorization);
        String Authorization = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImRlYW4iLCJleHAiOjE3MTQ0NjU5Njl9.QdCBYR8mioXcKGi1n5RdMQ5RbJHCSGbE8dkdwYuOXh4";
        if (!authorization.equals(Authorization)) {
            return Result.error("sign 验证不通过");
        }
        boolean result = okkiSiteService.okkiChangeStatus(param);
        log.info("请求成功，返回结果" + result);
        if (result == true) {
            return Result.OK("编辑成功！");
        } else {
            return Result.error("编辑失败！");
        }
    }

    /**
     * 更新飞书表格：建站顾问、组建站专员和组资料员字段
     *
     * @param recordSheetDto
     * @param authorization
     * @return
     */
    @PostMapping(value = "/feishu/update/table/record")
    public Result<?> feiShuUpdateTableRecord(FeiShuRecordSheetDto recordSheetDto, @RequestHeader(HttpHeaders.AUTHORIZATION) String authorization) {
        log.info("请求参数 recordSheetDto:{}", FastJsonUtil.toJSONString(recordSheetDto));
        log.info("请求参数 authorization:{}", authorization);
        String Authorization = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImRlYW4iLCJleHAiOjE3MTQ0NjU5Njl9.QdCBYR8mioXcKGi1n5RdMQ5RbJHCSGbE8dkdwYuOXh4";
        if (!authorization.equals(Authorization)) {
            return Result.error("sign 验证不通过");
        }
//        boolean res = feiShuSheetService.updateFeiShuTableSheetField(recordSheetDto);
        return Result.ok();
    }

    /**
     * 同步飞书表格-seo团队的外链表
     *
     * @param recordSheetDto
     * @param authorization
     * @return
     */
    @PostMapping(value = "/feishu/sync/seo/external/record")
    public Result<?> feiShuSyncSeoExternalRecord(FeiShuSeoTeamRecordSheetDto recordSheetDto, @RequestHeader(HttpHeaders.AUTHORIZATION) String authorization) {
        log.info("请求参数 recordSheetDto:{}", FastJsonUtil.toJSONString(recordSheetDto));
        log.info("请求参数 authorization:{}", authorization);
        String Authorization = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImRlYW4iLCJleHAiOjE3MTQ0NjU5Njl9.QdCBYR8mioXcKGi1n5RdMQ5RbJHCSGbE8dkdwYuOXh4";
        if (!authorization.equals(Authorization)) {
            return Result.error("sign 验证不通过");
        }

        if (StringUtils.isBlank(recordSheetDto.getExternalLink())) {
            feiShuMsgService.sendSyncSeoExternalLinkMsg(recordSheetDto.getCustomerName(), recordSheetDto.getSeoMemberFeiShuUnionId(), recordSheetDto.getSiteId(), recordSheetDto.getExternalLink(), "该客户缺少SEO外链文档，请检查");
            return Result.error("缺少SEO外链文档");
        }
        feiShuSeoTeamSheetService.syncSeoExternalLink(recordSheetDto);
        return Result.ok();
    }

    /**
     * 创建飞书seo外链表格
     *
     * @param recordSheetDto
     * @param authorization
     * @return
     */
    @PostMapping(value = "/feishu/create/seo/external/bitable")
    public Result<?> createFeiShuSeoExternalBitable(FeiShuSeoTeamRecordSheetDto recordSheetDto, @RequestHeader(HttpHeaders.AUTHORIZATION) String authorization) {
        log.info("请求参数 recordSheetDto:{}", FastJsonUtil.toJSONString(recordSheetDto));
        log.info("请求参数 authorization:{}", authorization);
        String Authorization = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImRlYW4iLCJleHAiOjE3MTQ0NjU5Njl9.QdCBYR8mioXcKGi1n5RdMQ5RbJHCSGbE8dkdwYuOXh4";
        if (!authorization.equals(Authorization)) {
            return Result.error("sign 验证不通过");
        }

        feiShuSheetService.createFeiShuSeoExternalBitable(recordSheetDto);
        return Result.ok();
    }

    /**
     * 创建客户飞书showlist基表
     *
     * @param recordSheetDto
     * @param authorization
     * @return
     */
    @PostMapping(value = "/feishu/create/seo/showlist/bitable")
    public Result<?> createFeiShuSeoShowlistBitable(FeiShuSeoTeamRecordSheetDto recordSheetDto, @RequestHeader(HttpHeaders.AUTHORIZATION) String authorization) {
        log.info("请求参数 recordSheetDto:{}", FastJsonUtil.toJSONString(recordSheetDto));
        log.info("请求参数 authorization:{}", authorization);
        String Authorization = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImRlYW4iLCJleHAiOjE3MTQ0NjU5Njl9.QdCBYR8mioXcKGi1n5RdMQ5RbJHCSGbE8dkdwYuOXh4";
        if (!authorization.equals(Authorization)) {
            return Result.error("sign 验证不通过");
        }

        feiShuSheetService.createFeiShuSeoShowlistBitable(recordSheetDto);
        return Result.ok();
    }

    /**
     * 根据站点ID获取企微群组消息
     *
     * @param weChatMsgDto
     * @param authorization
     * @return
     */
    @PostMapping(value = "/get/site/wechat/msg")
    public Result<?> getSiteWeChatMsg(@RequestBody WeChatMsgDto weChatMsgDto, @RequestHeader(HttpHeaders.AUTHORIZATION) String authorization) {
        log.info("请求参数 weChatMsgDto:{}", FastJsonUtil.toJSONString(weChatMsgDto));
        log.info("请求参数 authorization:{}", authorization);
        String Authorization = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImRlYW4iLCJleHAiOjE3MTQ0NjU5Njl9.QdCBYR8mioXcKGi1n5RdMQ5RbJHCSGbE8dkdwYuOXh4";
        if (!authorization.equals(Authorization)) {
            return Result.error("sign 验证不通过");
        }
        if (StringUtils.isBlank(weChatMsgDto.getSiteId()) || StringUtils.isBlank(weChatMsgDto.getLimit().toString())) {
            return Result.error("siteId 和 limit参数不能为空");
        }
        List<OkkiShopWechatGroupMsg> okkiShopWechatGroupMsgs = okkiShopWechatGroupMsgService.getSiteWechatMsgBySiteId(weChatMsgDto);
        return Result.ok(okkiShopWechatGroupMsgs);
    }

    /**
     * 处理okki站点信息
     *
     * @param authorization
     * @return
     */
    @PostMapping(value = "/upload/site/info")
    public Result<?> dealUploadSiteInfo(@RequestParam("files") MultipartFile files, @RequestHeader(HttpHeaders.AUTHORIZATION) String authorization) throws IOException {
        Map<String, Object> map = new HashMap<>();
        log.info("请求参数 authorization:{}", authorization);
        String Authorization = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImRlYW4iLCJleHAiOjE3MTQ0NjU5Njl9.QdCBYR8mioXcKGi1n5RdMQ5RbJHCSGbE8dkdwYuOXh4";
        if (!authorization.equals(Authorization)) {
            return Result.error("sign 验证不通过");
        }

        //获取原始文件名
        String originalFilename = files.getOriginalFilename();
        log.info("originalFilename:{}", originalFilename);

        //获取文件文件扩展名
        String extname = originalFilename.substring(originalFilename.lastIndexOf("."));
        log.info("extname:{}", extname);
        if (!extname.contains("json")) {
            map.put("status", 502);
            return Result.error("文件格式不正确");
        }

        //随机名+文件扩展名
        String newFileName = UUID.randomUUID() + extname;
        log.info("newFileName:{}", newFileName);

        String pathDir = fileJsonPath + "/" + newFileName;
        files.transferTo(new File(pathDir));

        boolean result = okkiSiteService.dealSiteInfoByJsonData(pathDir);
        if (result) {
            return Result.ok("同步站点信息成功");
        }
        return Result.error("同步站点信息失败");
    }
}
