package com.ibeetl.admin.flow.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.kevinsawicki.http.HttpRequest;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.annotation.LogController;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.admin.flow.entity.DirectedChannelEntity;
import com.ibeetl.admin.flow.entity.DirectedChannelUrlEntity;
import com.ibeetl.admin.flow.entity.DirectedFestivalEntity;
import com.ibeetl.admin.flow.query.QueryDirectedChannelUrl;
import com.ibeetl.admin.flow.service.DirectedChannelService;
import com.ibeetl.admin.flow.service.DirectedChannelUrlService;
import com.ibeetl.admin.flow.service.DirectedFestivalService;
import com.ibeetl.admin.flow.utils.RandomUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.List;

/**
 * 前向渠道链接管理
 *
 * @author Tao
 */
@Controller
public class DirectedChannelUrlController {
    private static final String MODEL = "/directed/channelUrl";
    private final Log log = LogFactory.getLog(this.getClass());

    @Autowired
    private DirectedChannelUrlService channelUrlService;

    @Autowired
    private DirectedFestivalService festivalService;

    @Autowired
    private DirectedChannelService channelService;

    @Value("${shorturl.url}")
    private String shorturl;

    @Value("${shorturl.password}")
    private String password;

    @GetMapping(MODEL + "/index.do")
    @Function("channelUrl.index")
    @LogController(content = "生成短连接", type = "2", description = "")
    // 用户免费资源查询
    public ModelAndView index(HttpServletRequest request,
                              HttpServletResponse response) {
        ModelAndView mv = new ModelAndView("/directed/channelurl/index.html");
        mv.addObject("search", DirectedChannelUrlEntity.class.getName());
        return mv;
    }

    @PostMapping(MODEL + "/list.json")
    @Function("channelUrl.index")
    @ResponseBody
    @LogController(content = "渠道链接查询", type = "2", description = "")
    public JsonResult<PageQuery<DirectedChannelUrlEntity>> index(QueryDirectedChannelUrl condition) {
        PageQuery<DirectedChannelUrlEntity> page = condition.getPageQuery();

        channelUrlService.searchChannelUrl(page);
        return JsonResult.success(page);
    }

    @GetMapping(MODEL + "/add.do")
    @Function("channelUrl.index")
    public ModelAndView add() {
        ModelAndView view = new ModelAndView("/directed/channelurl/add.html");
        return view;
    }

    @PostMapping(MODEL + "/add.json")
    @Function("channelUrl.index")
    @ResponseBody
    @LogController(content = "渠道URL添加", type = "2", description = "")
    public JsonResult add(String festivalid, String channelid) {
        try {
            saveChannelFestivalAndUrl(festivalid, channelid);
        } catch (Exception e) {
            return JsonResult.failMessage(e.getMessage());
        }

        return JsonResult.successMessage("保存成功");
    }

    private void saveChannelFestivalAndUrl(String festivalid, String channelid) {
        DirectedFestivalEntity festivalEntity = festivalService.findById(festivalid);

        DirectedFestivalEntity parityEntity = festivalService.findByFescod(festivalEntity.getParitycode());
        DirectedChannelEntity channelEntity = channelService.findChannelById(channelid);

        Assert.hasLength(festivalEntity.getUrl(), "活动的url未配置，请到活动管理中配置!");

        String url = festivalEntity.getUrl();
        if (festivalEntity.getUrl().indexOf("?") >= 0) {
            url = festivalEntity.getUrl().substring(0, festivalEntity.getUrl().indexOf("?"));
        }

        url += "?fes=" + festivalEntity.getFes();

        DirectedChannelUrlEntity entity = new DirectedChannelUrlEntity();

        entity.setFescod(festivalEntity.getFescod());
        entity.setFesname(festivalEntity.getFesname());
        entity.setOrderchannel(channelEntity.getOrderchannel());
        entity.setChannelname(channelEntity.getChannelname());
        entity.setUrl(url + "&sou=" + channelEntity.getSou());

        entity.setChannelid(channelEntity.getId());
        entity.setFesid(festivalEntity.getId());

        if (parityEntity != null) {
            entity.setParitycode(parityEntity.getFescod());
        }

        List<DirectedChannelUrlEntity> list = channelUrlService.findByFesAndChannel(
                entity.getFescod(), entity.getOrderchannel());

        Assert.isTrue(list == null || list.size() <= 0, "该活动和该渠道已经配置了链接!");

        channelUrlService.saveChannelFestivalAndUrl(entity);
    }

    @GetMapping(MODEL + "/edit.do")
    @Function("channelUrl.index")
    public ModelAndView edit(String id) {
        ModelAndView view = new ModelAndView("/directed/channelurl/edit.html");
        view.addObject("entity", channelUrlService.findChannelUrlById(id));
        return view;
    }

    @PostMapping(MODEL + "/edit.json")
    @Function("channelUrl.index")
    @ResponseBody
    @LogController(content = "渠道URL编辑", type = "2", description = "")
    public JsonResult edit(String id, String festivalid, String channelid) {

        DirectedFestivalEntity festivalEntity = festivalService.findById(festivalid);
        DirectedChannelEntity channelEntity = channelService.findChannelById(channelid);

        Assert.hasLength(festivalEntity.getUrl(), "活动的url未配置，请到活动管理中配置!");

        String url = festivalEntity.getUrl();
        if (festivalEntity.getUrl().indexOf("?") >= 0) {
            url = festivalEntity.getUrl().substring(0, festivalEntity.getUrl().indexOf("?"));
            url += "?fes=" + festivalEntity.getFes();
        }

        DirectedChannelUrlEntity entity = new DirectedChannelUrlEntity();
        entity.setId(id);
        entity.setFescod(festivalEntity.getFescod());
        entity.setFesname(festivalEntity.getFesname());
        entity.setOrderchannel(channelEntity.getOrderchannel());
        entity.setChannelname(channelEntity.getChannelname());
        entity.setUrl(url + "&sou=" + channelEntity.getSou());

        channelUrlService.updateChannelUrl(entity);

        return JsonResult.success(entity.getId());
    }

    @PostMapping(MODEL + "/del.json")
    @Function("channelUrl.index")
    @ResponseBody
    @LogController(content = "渠道URL删除", type = "2", description = "")
    public JsonResult del(DirectedChannelUrlEntity directedChannelUrlEntity) {

        DirectedChannelUrlEntity temp = channelUrlService.findChannelUrlById(directedChannelUrlEntity.getId());

        if (temp == null) {
            saveChannelFestivalAndUrl(directedChannelUrlEntity.getFescod(), directedChannelUrlEntity.getChannelid());
            temp = channelUrlService.findChannelUrlById(directedChannelUrlEntity.getId());

            if (temp == null) {
                return JsonResult.failMessage("ID不存在");
            }
        }

        temp.setChannelid(directedChannelUrlEntity.getChannelid());

        DirectedFestivalEntity festaval = festivalService.findByFescod(directedChannelUrlEntity.getFescod());
        temp.setParitycode(festaval.getParitycode());

        channelUrlService.deleteChannelUrl(temp);

        return JsonResult.successMessage("删除成功");
    }

    @GetMapping(MODEL + "/myqrcode.do")
    @Function("channelUrl.index")
    public ModelAndView ercode(String id) {

        DirectedChannelUrlEntity temp = channelUrlService.findChannelUrlById(id);

        ModelAndView view = new ModelAndView("/directed/channelurl/myqrcode.html");
        view.addObject("entity", temp);

        return view;
    }

    @PostMapping(MODEL + "/shortUrl.json")
    @Function("channelUrl.index")
    @ResponseBody
    @LogController(content = "生成短网址", type = "2", description = "")
    public JsonResult shortUrl(String id, String fescod, String channelid, String orderchannel) {
        try {
            DirectedFestivalEntity festivalEntity = festivalService.findByFescod(fescod);
            Assert.hasLength(festivalEntity.getUrl(), "请先到活动管理中配置活动的url!");

            DirectedChannelUrlEntity temp = channelUrlService.findChannelUrlById(id);

            if (temp == null) {
                saveChannelUrl(festivalEntity, channelid);
                temp = channelUrlService.findByFesAndChannel(fescod, orderchannel).get(0);
            }

            String code = "";
            if (StringUtils.isEmpty(temp.getShorturl()) ||
                    temp.getShorturl().indexOf("/s/") < 0) {
                code = RandomUtil.random(6, RandomUtil.LOWER_UPPER_NUMBER);
                temp.setShorturl("https://800.wo.cn/s/" + code);
            } else {
                code = temp.getShorturl().substring(temp.getShorturl().indexOf("/s/") + 3);
            }

            String sign = DigestUtils.md5Hex(temp.getUrl() + code + "true" + password);

            HttpRequest request = HttpRequest.post(shorturl + "?shortCode=" + code + "&url=" + URLEncoder.encode(temp.getUrl(), "UTF-8") + "&cover=" + true + "&sign=" + sign);
            String result = new String(request.bytes(), Charset.forName("UTF-8"));

            log.info("生成短网址：" + temp.getUrl() + "，" + temp.getShorturl() + "，结果：" + result);

            JSONObject jsonObject = JSONObject.parseObject(result);
            if ("0000".equals(jsonObject.getString("resultCode"))) {
                channelUrlService.updateChannelUrl(temp);
                return JsonResult.successMessage("生成短网址成功");
            }
            return JsonResult.failMessage(jsonObject.getString("errorInfo"));
        } catch (Exception e) {
            return JsonResult.failMessage(e.getMessage());
        }
    }

    private void saveChannelUrl(DirectedFestivalEntity festivalEntity, String channelid) {
        DirectedFestivalEntity parityEntity = festivalService.findByFescod(festivalEntity.getParitycode());
        DirectedChannelEntity channelEntity = channelService.findChannelById(channelid);

        Assert.hasLength(festivalEntity.getUrl(), "请先到活动管理中配置活动的url!");

        String url = festivalEntity.getUrl();
        if (festivalEntity.getUrl().indexOf("?") >= 0) {
            url = festivalEntity.getUrl().substring(0, festivalEntity.getUrl().indexOf("?"));
        }

        url += "?fes=" + festivalEntity.getFes();

        DirectedChannelUrlEntity entity = new DirectedChannelUrlEntity();

        entity.setFescod(festivalEntity.getFescod());
        entity.setFesname(festivalEntity.getFesname());
        entity.setOrderchannel(channelEntity.getOrderchannel());
        entity.setChannelname(channelEntity.getChannelname());
        entity.setUrl(url + "&sou=" + channelEntity.getSou());

        entity.setChannelid(channelEntity.getId());
        entity.setFesid(festivalEntity.getId());

        if (parityEntity != null) {
            entity.setParitycode(parityEntity.getFescod());
        }

        channelUrlService.saveChannelUrl(entity);
    }

}
