package com.fs.company.controller;

import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.fs.common.annotation.RepeatSubmit;
import com.fs.common.core.domain.R;
import com.fs.common.param.SmsSendBatchParam;
import com.fs.common.service.ISmsService;
import com.fs.common.utils.ServletUtils;
import com.fs.common.utils.StringUtils;
import com.fs.common.utils.http.HttpUtils;
import com.fs.company.param.CompanyUserCardQueryParam;
import com.fs.core.security.LoginUser;
import com.fs.core.web.service.TokenService;
import com.fs.wx.miniapp.config.WxMaProperties;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.fs.common.annotation.Log;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.enums.BusinessType;
import com.fs.company.domain.CompanyUserCard;
import com.fs.company.service.ICompanyUserCardService;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.common.core.page.TableDataInfo;

/**
 * CompanyUserCardController
 *
 * @author fs
 * @date 2023-04-28
 */
@RestController
@RequestMapping("/company/companUsercard")
public class CompanyUserCardController extends BaseController
{
    @Autowired
    private ICompanyUserCardService companyUserCardService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ISmsService smsService;

    @Autowired
    private WxMaProperties properties;
    private String aifabuAppId="7b471be905ab17e00f3b858c6710dd117601d008";

    /**
     * 查询card列表
     */
    @PreAuthorize("@ss.hasPermi('company:companUsercard:list')")
    @GetMapping("/list")
    public TableDataInfo list(CompanyUserCardQueryParam param)
    {
        startPage();
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        param.setCompanyId(loginUser.getCompany().getCompanyId());
        param.setCompanyUserId(loginUser.getUser().getUserId());
        List<CompanyUserCard> list = companyUserCardService.selectMyCardListQuery(param);
        return getDataTable(list);
    }

    /**
     * 导出card列表
     */
    @PreAuthorize("@ss.hasPermi('company:companUsercard:export')")
    @Log(title = "card", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(CompanyUserCard companyUserCard)
    {
        List<CompanyUserCard> list = companyUserCardService.selectCompanyUserCardList(companyUserCard);
        ExcelUtil<CompanyUserCard> util = new ExcelUtil<CompanyUserCard>(CompanyUserCard.class);
        return util.exportExcel(list, "card");
    }

    /**
     * 获取card详细信息
     */
    @PreAuthorize("@ss.hasPermi('company:companUsercard:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(companyUserCardService.selectCompanyUserCardById(id));
    }

    /**
     * 新增card
     */
    @PreAuthorize("@ss.hasPermi('company:companUsercard:add')")
    @Log(title = "card", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CompanyUserCard companyUserCard)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        companyUserCard.setUserId(loginUser.getUser().getUserId());
        companyUserCard.setCompanyId(loginUser.getCompany().getCompanyId());
        companyUserCard.setCreateTime(new Date());
        int rows=companyUserCardService.insertCompanyUserCard(companyUserCard);
        if(rows>0){
            String shorUrl=this.getShortUrlAction(companyUserCard.getId(),companyUserCard.getTitle());
            companyUserCard.setShortUrl(shorUrl);
            if(companyUserCardService.updateUserCardShortUrlById(companyUserCard.getId(),shorUrl)>0){
                return toAjax(1);
            }
        }
        return toAjax(0);
    }

    /**
     * 修改card
     */
    @PreAuthorize("@ss.hasPermi('company:companUsercard:edit')")
    @Log(title = "card", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CompanyUserCard companyUserCard)
    {
        companyUserCard.setUpdateTime(new Date());
        return toAjax(companyUserCardService.updateCompanyUserCard(companyUserCard));
    }

    /**
     * 删除card
     */
    @PreAuthorize("@ss.hasPermi('company:companUsercard:remove')")
    @Log(title = "card", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(companyUserCardService.deleteCompanyUserCardByIds(ids));
    }


    @PostMapping("/sendCustomerBatchMsg")
    @RepeatSubmit
    @Transactional
    public R sendCustomerBatchMsg(@Validated @RequestBody SmsSendBatchParam param){
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        param.setCompanyId(loginUser.getCompany().getCompanyId());
        param.setCompanyUserId(loginUser.getUser().getUserId());
        return smsService.sendBatchSms(param);
    }


    private String getShortUrlAction(Long cardId,String title){
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("apikey",aifabuAppId);
            String url="http://company.yjf.runtzh.com/wx.html?id="+cardId;
            jsonObject.put("target_url",url);
            jsonObject.put("group_id",308195);
            if(StringUtils.isNotEmpty(title)){
                jsonObject.put("chain_title",title);
            }
            String paramStr=jsonObject.toJSONString();
            String postStr = HttpUtils.doPost("https://openapi.aifabu.com/v1/chain/createChain",paramStr);
            JSONObject obj = JSONObject.parseObject(postStr);
            Integer code= obj.getInteger("code");
            String shortUrl="";
            if(code==1){
                JSONObject result = obj.getJSONObject("result");
                shortUrl=result.getString("render_url");
            }
            return shortUrl;
        }
        catch (Exception e) {
            return "";
        }
    }


    @ApiOperation("获取短链接")
    @GetMapping("/getShortUrl")
    public R getShortUrl(@RequestParam(value = "url") String url, @RequestParam(value = "title") String title)
    {
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("apikey",aifabuAppId);
            jsonObject.put("target_url",url);
            jsonObject.put("group_id",308195);
            if(StringUtils.isNotEmpty(title)){
                jsonObject.put("chain_title",title);
            }
            String paramStr=jsonObject.toJSONString();
            String postStr = HttpUtils.doPost("https://openapi.aifabu.com/v1/chain/createChain",paramStr);
            JSONObject obj = JSONObject.parseObject(postStr);
            return R.ok().put("data",obj);
        }
        catch (Exception e) {
            return R.error("操作失败");
        }
    }

}
