package com.huiju.estateagents.eContract.controller;

import com.alibaba.fastjson.JSONObject;
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.huiju.estateagents.base.BaseController;
import com.huiju.estateagents.base.ResponseBean;
import com.huiju.estateagents.common.CommConstant;
import com.huiju.estateagents.common.StringUtils;
import com.huiju.estateagents.eContract.entity.TaCompany;
import com.huiju.estateagents.eContract.entity.TaCompanySeal;
import com.huiju.estateagents.eContract.service.ITaCompanySealService;
import com.huiju.estateagents.eContract.service.ITaCompanyService;
import com.huiju.estateagents.eContract.service.impl.TaCompanySealUtil;
import com.huiju.estateagents.entity.TaMiniapp;
import com.huiju.estateagents.service.impl.TaMiniappServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * <p>
    * 公司印章  前端控制器
    * </p>
 *
 * @author fxf
 * @since 2020-03-26
 */
@RestController
@RequestMapping("/api")
public class TaCompanySealController extends BaseController {

    private final Logger logger = LoggerFactory.getLogger(TaCompanySealController.class);

    @Autowired
    public ITaCompanySealService iTaCompanySealService;

    @Autowired
    private ITaCompanyService iTaCompanyService;

    @Autowired
    private TaCompanySealUtil taCompanySealUtil;

    @Autowired
    private TaMiniappServiceImpl taMiniappService;

    /**
     * 分页查询列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value="/admin/taCompanySeal",method= RequestMethod.GET)
    public ResponseBean taCompanySealList(@RequestParam(value ="pageNum",defaultValue = "1") Integer pageNum,
                                          @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize,
                                          @RequestParam(value ="sealName", required = false) String sealName,
                                          @RequestParam(value ="companyId", required = false) String companyId){
        ResponseBean responseBean = new ResponseBean();
        try {
            //使用分页插件
		    IPage<TaCompanySeal> pg = new Page<>(pageNum, pageSize);
            QueryWrapper<TaCompanySeal> queryWrapper = new QueryWrapper<>();
            queryWrapper.like(!StringUtils.isEmpty(sealName), "seal_name", sealName);
            queryWrapper.ne("status", CommConstant.STATUS_DELETE);
            queryWrapper.eq(!StringUtils.isEmpty(companyId), "company_id", companyId);
            queryWrapper.orderByDesc("create_date");

            IPage<TaCompanySeal> result = iTaCompanySealService.page(pg, queryWrapper);
            responseBean.addSuccess(result);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taCompanySealList -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 分页查询列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value="/channel/taCompanySeal",method= RequestMethod.GET)
    public ResponseBean channelCompanySealList(
                                          @RequestParam(value ="pageNum",defaultValue = "1") Integer pageNum,
                                          @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize,
                                          @RequestParam(value ="companyId", required = false) String companyId,
                                          @RequestParam(value ="sealName", required = false) String sealName){
        ResponseBean responseBean = new ResponseBean();
        try {
            //使用分页插件
            IPage<TaCompanySeal> pg = new Page<>(pageNum, pageSize);
            QueryWrapper<TaCompanySeal> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("company_id", companyId);
            queryWrapper.like(!StringUtils.isEmpty(sealName), "seal_name", sealName);
            queryWrapper.ne("status", CommConstant.STATUS_DELETE);
            queryWrapper.orderByDesc("create_date");

            IPage<TaCompanySeal> result = iTaCompanySealService.page(pg, queryWrapper);
            responseBean.addSuccess(result);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taCompanySealList -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 保存对象
     * @param taCompanySeal 实体对象
     * @return
     */
    @RequestMapping(value="/channel/taCompanySeal",method= RequestMethod.POST)
    public ResponseBean taCompanySealAdd(@RequestBody TaCompanySeal taCompanySeal, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            TaCompany taCompany = iTaCompanyService.getById(taCompanySeal.getCompanyId());
            String result = taCompanySealUtil.addSignaTure(taCompany.getFadadaCode(), taCompanySeal.getSealImg());
            JSONObject params = JSONObject.parseObject(result);
            if ((Integer) params.get("code") != 1){
                responseBean.addError(params.get("msg").toString());
                return responseBean;
            }

            String data = params.getString("data");
            taCompanySeal.setCreateDate(LocalDateTime.now());
            taCompanySeal.setStatus(CommConstant.STATUS_NORMAL);
            taCompanySeal.setSignatureId(JSONObject.parseObject(data).getString("signature_id"));
            if (iTaCompanySealService.save(taCompanySeal)){
                responseBean.addSuccess(taCompanySeal);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taCompanySealAdd -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id删除对象
     * @param id  实体ID
     */
    @RequestMapping(value="/channel/deleteCompanySeal/{id}",method= RequestMethod.PUT)
    public ResponseBean taCompanySealDelete(@PathVariable Integer id){
        ResponseBean responseBean = new ResponseBean();
        try {
            TaCompanySeal taCompanySeal = iTaCompanySealService.getById(id);
            TaCompany taCompany = iTaCompanyService.getById(taCompanySeal.getCompanyId());
            iTaCompanyService.getById(taCompanySeal.getCompanyId());
            String res = taCompanySealUtil.delSignature(taCompany.getFadadaCode(), taCompanySeal.getSignatureId());
            JSONObject params = JSONObject.parseObject(res);
            Integer code = (Integer) params.get("code");
            if (code != 1){
                responseBean.addError(params.getString("msg"));
                return responseBean;
            }

            TaCompanySeal delInfo = new TaCompanySeal();
            delInfo.setSealId(id);
            delInfo.setStatus(CommConstant.STATUS_DELETE);
            if(iTaCompanySealService.updateById(delInfo)){
                responseBean.addSuccess("success");
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taCompanySealDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 修改对象
     * @param id  实体ID
     * @param taCompanySeal 实体对象
     * @return
     */
    @RequestMapping(value="/channel/taCompanySeal/{id}",method= RequestMethod.PUT)
    public ResponseBean taCompanySealUpdate(@PathVariable Integer id,
                                        @RequestBody TaCompanySeal taCompanySeal, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            TaCompany taCompany = iTaCompanyService.getById(taCompanySeal.getCompanyId());
            TaCompanySeal sealInfo = iTaCompanySealService.getById(id);
            String res = taCompanySealUtil.replaceSignature(taCompany.getFadadaCode(), sealInfo.getSignatureId(), taCompanySeal.getSealImg());
            JSONObject params = JSONObject.parseObject(res);
            Integer code = (Integer) params.get("code");
            if (code != 1){
                responseBean.addError(params.getString("msg"));
                return responseBean;
            }
            taCompanySeal.setSealId(id);
            if (iTaCompanySealService.updateById(taCompanySeal)){
                responseBean.addSuccess(taCompanySeal);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taCompanySealUpdate -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id查询对象
     * @param id  实体ID
     */
    @RequestMapping(value="/channel/taCompanySeal/{id}",method= RequestMethod.GET)
    public ResponseBean taCompanySealGet(@PathVariable Integer id){
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean.addSuccess(iTaCompanySealService.getById(id));
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taCompanySealDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id查询公司授权对象信息
     * @param id  实体ID
     */
    @RequestMapping(value = "/channel/companySignInfo/id")
    public ResponseBean companySignInfoByCompanyId(@PathVariable Integer id){
        ResponseBean responseBean = new ResponseBean();
        try {
            
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taCompanySealDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }
}
