package cn.iocoder.yudao.module.contract.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.contract.entity.ContractHistory;
import cn.iocoder.yudao.module.contract.entity.ContractSignVo;
import cn.iocoder.yudao.module.contract.entity.InspectionContract;
import cn.iocoder.yudao.module.contract.service.IContractHistoryService;
import cn.iocoder.yudao.module.contract.service.IInspectionContractService;
import cn.iocoder.yudao.module.core.controller.BaseController;
import cn.iocoder.yudao.module.infra.service.file.FileService;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import cn.iocoder.yudao.util.ExcelUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.List;

import static cn.iocoder.yudao.module.contract.utils.ImageUtil.base64ToJpg;

/**
 * 签署历史Controller
 *
 * @author ruoyi
 * @date 2023-07-19
 */
@RestController
@RequestMapping("/admin-api/system/history")
public class ContractHistoryController extends BaseController
{
    @Autowired
    private AdminUserService userService;
    @Autowired
    private IContractHistoryService contractHistoryService;
    @Autowired
    private IInspectionContractService inspectionContractService;
    @Resource
    private FileService fileService;

    /**
     * 查询签署历史列表
     */
//    @PreAuthorize("@ss.hasPermi('system:history:list')")
    @GetMapping("/list")
    public CommonResult list(ContractHistory contractHistory,
                             @RequestParam(value = "pageNum" ,required = false ,defaultValue = "1") Integer pageNum,
                             @RequestParam(value ="pageSize" ,required = false ,defaultValue = "10") Integer pageSize)
    {
        Page<ContractHistory> page = new Page<>(pageNum, pageSize);
        IPage<ContractHistory> list = contractHistoryService.selectContractHistoryList(page,contractHistory);
        return success(list);
    }

    /**
     * 导出签署历史列表
     */
//    @PreAuthorize("@ss.hasPermi('system:history:export')")

    @PostMapping("/export")
    public void export(HttpServletResponse response, ContractHistory contractHistory,
                       @RequestParam(value = "pageNum" ,required = false ,defaultValue = "1") Integer pageNum,
                       @RequestParam(value ="pageSize" ,required = false ,defaultValue = "10") Integer pageSize)
    {
        Page<ContractHistory> page = new Page<>(pageNum, pageSize);
        IPage<ContractHistory> list = contractHistoryService.selectContractHistoryList(page,contractHistory);
        ExcelUtil<ContractHistory> util = new ExcelUtil<ContractHistory>(ContractHistory.class);
        util.exportExcel(response, list.getRecords(), "签署历史数据");
    }

    /**
     * 获取签署历史详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:history:query')")
    @GetMapping(value = "/{id}")
    public CommonResult getInfo(@PathVariable("id") Long id)
    {
        return success(contractHistoryService.selectContractHistoryById(id));
    }

    /**
     * 新增签署历史
     */

    @PostMapping
    public CommonResult add(@RequestBody ContractSignVo data) throws IOException, DocumentException {
        Calendar calendar = Calendar.getInstance();
        // 获取当前年
        int year = calendar.get(Calendar.YEAR);
        // 获取当前月
        int month = calendar.get(Calendar.MONTH) + 1;
        // 获取当前日
        int day = calendar.get(Calendar.DATE);
        ContractHistory contractHistory =new ContractHistory();
        LoginUser nowUser = SecurityFrameworkUtils.getLoginUser();
        contractHistory.setContractId(1L);
        contractHistory.setUserId(nowUser.getId());
        //实体对象转成map
        JSONObject dataMap =new JSONObject();
        dataMap.put("sfz",data.getSfz());
        dataMap.put("position",data.getPosition());
        dataMap.put("carNum",data.getCarNum());
        dataMap.put("phone",data.getPhone());
        dataMap.put("cbgs",data.getCbgs());
        dataMap.put("kcyPhone",data.getKcyPhone());
        dataMap.put("lc",data.getLc());
        dataMap.put("rs",data.getRs());
        dataMap.put("sjqk",data.getSjqk());
        dataMap.put("jbr",data.getJbr());
        dataMap.put("year",String.valueOf(year));
        dataMap.put("month",String.valueOf(month));
        dataMap.put("day",String.valueOf(day));
        byte[] decode = Base64.decode(data.getSignImage());
        String url = fileService.createFile("temp", null, decode);
        contractHistory.setSignContract(url);
        return success(contractHistoryService.insertContractHistory(contractHistory));
    }



    /**
     * 新增检测委托授权
     */

    @PostMapping("/jcWts")
    public CommonResult jcWts(@RequestBody InspectionContract data) throws Exception {
        //当前登录用户
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        Calendar calendar = Calendar.getInstance();
        // 获取当前年
        int year = calendar.get(Calendar.YEAR);
        // 获取当前月
        int month = calendar.get(Calendar.MONTH) + 1;
        // 获取当前日
        int day = calendar.get(Calendar.DATE);
        //判断当前年是否已存在授权 当前车
        LambdaQueryWrapper<InspectionContract> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(InspectionContract::getUserId,loginUser.getId())
                .eq(InspectionContract::getCarnum,data.getCarnum()).like(InspectionContract::getYear,year);
        InspectionContract one = inspectionContractService.getOne(queryWrapper);
        if (ObjectUtil.isNotEmpty(one)){
            throw new Exception("请不要重复授权");
        }
        AdminUserDO user = userService.getUser(loginUser.getId());
        AdminUserDO wtrUser = userService.getUser(data.getWtrId());
        data.setYear(year);
        data.setMonth(month);
        data.setDay(day);
        data.setUserId(user.getId());
        data.setBren(user.getNickname());
        data.setBrphone(user.getMobile());
        data.setBrsfz(user.getIdCard());
        data.setWtr(wtrUser.getNickname());
        data.setWtrphone(wtrUser.getMobile());
        data.setWtrsfz(wtrUser.getIdCard());
        ContractHistory contractHistory =new ContractHistory();
        LoginUser nowUser = SecurityFrameworkUtils.getLoginUser();
        contractHistory.setContractId(2L);
        contractHistory.setUserId(nowUser.getId());
        //实体对象转成map
        JSONObject dataMap =JSONObject.parseObject(JSONObject.toJSONString(data));
        byte[] decode = Base64.decode(data.getSignImage());
        String url = fileService.createFile("temp", null, decode);
        contractHistory.setSignContract(url);
        inspectionContractService.save(data);
        return success(contractHistoryService.insertContractHistory(contractHistory));
    }
    /**
     * 修改签署历史
     */
//    @PreAuthorize("@ss.hasPermi('system:history:edit')")
    @PutMapping
    public CommonResult edit(@RequestBody ContractHistory contractHistory)
    {
        return toAjax(contractHistoryService.updateContractHistory(contractHistory));
    }

    /**
     * 删除签署历史
     */
//    @PreAuthorize("@ss.hasPermi('system:history:remove')")

	@DeleteMapping("/{ids}")
    public CommonResult remove(@PathVariable Long[] ids)
    {
        return toAjax(contractHistoryService.deleteContractHistoryByIds(ids));
    }

}
