/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.ykt.service.impl;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Joiner;
import me.zhengjie.modules.dm.dmCard.domain.DmCard;
import me.zhengjie.modules.dm.dmCard.service.DmCardService;
import me.zhengjie.modules.dm.dmLane.service.DmLaneService;
import me.zhengjie.modules.dm.dmLane.service.dto.DmLaneDto;
import me.zhengjie.modules.dm.dmLane.service.dto.DmLaneQueryCriteria;
import me.zhengjie.modules.dmuser.domain.DmUser;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.repository.UserRepository;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.modules.system.service.dto.UserDto;
import me.zhengjie.utils.*;
import me.zhengjie.ykt.domain.DmPlateNumber;
import lombok.RequiredArgsConstructor;
import me.zhengjie.ykt.repository.DmPlateNumberRepository;
import me.zhengjie.ykt.service.DmPlateNumberService;
import me.zhengjie.ykt.service.dto.DmPlateNumberDto;
import me.zhengjie.ykt.service.dto.DmPlateNumberQueryCriteria;
import me.zhengjie.ykt.service.mapstruct.DmPlateNumberMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.util.ObjectUtils;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author zhirong
* @date 2021-11-10
**/
@Service
@RequiredArgsConstructor
public class DmPlateNumberServiceImpl implements DmPlateNumberService {
    @Value("${yueUrl}")
    private String yueUrl;
    @Value("${mfUrl}")
    private String mfUrl;
    @Value("${deleteYueUrl}")
    private String deleteYueUrl;
    @Value("${messageUrl}")
    private String messageUrl;
    private final DmPlateNumberRepository dmPlateNumberRepository;
    private final DmPlateNumberMapper dmPlateNumberMapper;
    private final UserService userService;
    private final DmLaneService dmLaneService;
    private final UserRepository userRepository;
    private final DmCardService dmCardService;

    @Override
    public Map<String,Object> queryAll(DmPlateNumberQueryCriteria criteria, Pageable pageable){
        Page<DmPlateNumber> page = dmPlateNumberRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(dmPlateNumberMapper::toDto));
    }

    @Override
    public List<DmPlateNumberDto> queryAll(DmPlateNumberQueryCriteria criteria){
        return dmPlateNumberMapper.toDto(dmPlateNumberRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    public List<DmPlateNumber> yuePlateRepository() {
        return dmPlateNumberRepository.yuePlateRepository();
    }

    @Override
    public List<DmPlateNumber> mfPlateRepository() {
        return dmPlateNumberRepository.mfPlateRepository();
    }

    @Override
    @Transactional
    public DmPlateNumberDto findById(Long id) {
        DmPlateNumber dmPlateNumber = dmPlateNumberRepository.findById(id).orElseGet(DmPlateNumber::new);
        ValidationUtil.isNull(dmPlateNumber.getId(),"DmPlateNumber","id",id);
        return dmPlateNumberMapper.toDto(dmPlateNumber);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(DmPlateNumber resources) {
        Snowflake snowflake = IdUtil.createSnowflake(1, 1);
        resources.setId(snowflake.nextId());
        resources.setEffectiveState("00");//有效
        resources.setRegistrationStatus("01");//未审核
        resources.setType("01");//web
        resources.setCreateBy(SecurityUtils.getCurrentUsername());
        List<DmPlateNumber> count = dmPlateNumberRepository.getDmPlateNumberByCard(resources.getDmCard().getCardNumber());
        if (!ObjectUtils.isEmpty(count)){
            deleteYuePlate(count.get(0).getPlateNumber());
            DmPlateNumber dmPlateNumber = count.get(0);
            dmPlateNumber.setDmCard(resources.getDmCard());
            dmPlateNumber.setUserNumber(resources.getUserNumber());
            dmPlateNumber.setPlateNumber(resources.getPlateNumber());
            dmPlateNumber.setStartTime(resources.getStartTime());
            dmPlateNumber.setEndTime(resources.getEndTime());
            dmPlateNumber.setVehicleType(resources.getVehicleType());
            dmPlateNumber.setEffectiveState(resources.getEffectiveState());
            dmPlateNumber.setRegistrationStatus(resources.getRegistrationStatus());
            dmPlateNumber.setCreateTime(new Timestamp(System.currentTimeMillis()));
            ValidationUtil.isNull( dmPlateNumber.getId(),"DmPlateNumber","id",resources.getId());
            dmPlateNumber.copy(dmPlateNumber);
            dmPlateNumberRepository.save(dmPlateNumber);
            if (dmPlateNumber.getVehicleType().equals("00")){//员工
                addYuePlate(dmPlateNumber);
            }else if (dmPlateNumber.getVehicleType().equals("01")){//VIP
                mfReserveData(dmPlateNumber);
            }else if (dmPlateNumber.getVehicleType().equals("02")){//访客
                mfReserveData(dmPlateNumber);
            }
        }else{
            dmPlateNumberRepository.save(resources);
            if (resources.getVehicleType().equals("00")){//员工
                addYuePlate(resources);
            }else if (resources.getVehicleType().equals("01")){//VIP
                mfReserveData(resources);
            }else if (resources.getVehicleType().equals("02")){//访客
                mfReserveData(resources);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createApp(DmPlateNumber resources) throws ParseException {
        String isApprove = queryApprove();
        DmPlateNumber plateNumber = new DmPlateNumber();
        DmCard dmCard = dmCardService.findByUserNumber(resources.getUserNumber().getId());
        plateNumber.setDmCard(dmCard);
        plateNumber.setVehicleType("00");//访客车辆
        plateNumber.setEffectiveState("00");//有效
        if(StringUtils.equals(isApprove,"00")){
            plateNumber.setRegistrationStatus("01");//登记成功
        } else if(StringUtils.equals(isApprove,"01")) {
            plateNumber.setRegistrationStatus("00");//未审核
            String url = "https://portal.caih.com/api-third-party/busi/comm/collaboration/process/generateProc";
            String taskId = UUID.randomUUID().toString();
            JSONObject generateProcJson = new JSONObject();
            JSONObject formData = new JSONObject();
            formData.put("taskId",taskId);
            formData.put("number",resources.getPlateNumber());
            formData.put("text",resources.getRemark());
            formData.put("carType","员工车牌");
            formData.put("taskType","3");
            generateProcJson.put("formData",formData);
            User user = userRepository.getUserByDmUserId(resources.getUserNumber().getId());
            JSONObject caihRuRequestInfo = new JSONObject();
            caihRuRequestInfo.put("compId", user.getUserRootGroupId());
            caihRuRequestInfo.put("compName", user.getUserRootGroupName());
            caihRuRequestInfo.put("orgId", user.getDept().getId());
            caihRuRequestInfo.put("orgName", user.getDept().getName());
            caihRuRequestInfo.put("userId",user.getId());
            caihRuRequestInfo.put("userName",user.getNickName());
            caihRuRequestInfo.put("mobile",user.getPhone());
            generateProcJson.put("caihRuRequestInfo",caihRuRequestInfo);
            generateProcJson.put("procDefKey","CUST_e8d0cec5-2042-4730-a9ae-81bf4c2dd3e6");
            generateProcJson.put("procName","办公-永天流程申请");
            generateProcJson.put("tarTaskDefKey", "taskDefinitionKey2");
            generateProcJson.put("tenantId","caih");
            String generateProcData = HttpRequest.get(url).body(generateProcJson.toJSONString()).execute().body();
            System.out.println("generateProcData:"+generateProcData);
            plateNumber.setTaskId(taskId);
        }
        plateNumber.setType("00");//app
        plateNumber.setUserName(resources.getUserName());
        plateNumber.setUserPhone(resources.getUserPhone());
        plateNumber.setPlateNumber(resources.getPlateNumber());
        plateNumber.setRemark(resources.getRemark());
        plateNumber.setUserNumber(resources.getUserNumber());
        plateNumber.setStartTime(resources.getStartTime());
        plateNumber.setEndTime(resources.getEndTime());
        List<DmPlateNumber> count = dmPlateNumberRepository.getDmPlateNumberByCard(dmCard.getCardNumber());
        if (!ObjectUtils.isEmpty(count)){
            plateNumber.setId(count.get(0).getId());
            deleteYuePlate(count.get(0).getPlateNumber());
            dmPlateNumberRepository.save(plateNumber);
        }else{
            Snowflake snowflake = IdUtil.createSnowflake(1, 1);
            plateNumber.setId(snowflake.nextId());
            dmPlateNumberRepository.save(plateNumber);
        }
        if(StringUtils.equals(isApprove,"00")) {
            addYuePlate(plateNumber);
        }
        message(plateNumber);
    }

    @Override
    public void message(DmPlateNumber resources){
//        String url = "https://smartpark.caih.com/zkxt/api/thirdparty/v1/message/sendChatMessage";
        Map<String,Object> token = SecurityUtils.getToken("DMERPYT!@#$QWER2021+{:>");
        UserDto user = userService.findById(resources.getUserNumber().getId());
        JSONObject query = new JSONObject();
        query.put("systemName","一卡通系统");
        query.put("sendId","dm_plate_number|task_id|"+resources.getId());//taskId
        query.put("sendUserId",resources.getUserNumber().getId());
        JSONObject sendContentJSON = new JSONObject();
        sendContentJSON.put("text","您的车牌已登记!");
        query.put("sendContent",sendContentJSON);
        query.put("usernames",user.getUsername());
        JSONObject param = new JSONObject();
        param.put("nonce",token.get("nonce"));
        param.put("timestamp",token.get("timestamp"));
        param.put("query",query);
        HttpRequest.get(messageUrl).header("XYTACCESSTOKEN", token.get("token").toString()).body(param.toJSONString()).execute().body();

    }

    /**
     * 月租车
     * @param dto
     */
    @Override
    public void addYuePlate(DmPlateNumber dto){
//        String url = "http://10.208.128.14:9999/api/park/addmonthlycar";
        JSONObject generateProcJson = new JSONObject();
        generateProcJson.put("name",dto.getUserNumber().getName());
        generateProcJson.put("phone",dto.getUserNumber().getContacts());
        generateProcJson.put("carplate",dto.getPlateNumber());
        SimpleDateFormat formater2 = new SimpleDateFormat("yyyy-MM-dd");
        generateProcJson.put("startdate",formater2.format(dto.getStartTime()));
        generateProcJson.put("enddate",formater2.format(dto.getEndTime()));
        generateProcJson.put("cardtype","A");
        generateProcJson.put("controllers", "1,2,3,4");
        String generateProcData = BeanMapUtils.doPostForm(yueUrl,generateProcJson);
        JSONObject generateProcDataJson = JSONObject.parseObject(generateProcData);
        System.out.println("月租车data"+generateProcJson);
        System.out.println("add月租车:"+generateProcDataJson);
    }

    /**
     * 删除月租车
     */
    @Override
    public void deleteYuePlate(String carplate) {
//        String url = "http://10.208.128.14:9999/api/park/addfreecar";
        JSONObject generateProcJson = new JSONObject();
        generateProcJson.put("carplate",carplate);
        String generateProcData = BeanMapUtils.doPostForm(deleteYueUrl,generateProcJson);
        JSONObject generateProcDataJson = JSONObject.parseObject(generateProcData);
        System.out.println("删除月租车"+generateProcJson);
        System.out.println("删除月租车:"+generateProcDataJson);
    }

    /**
     * 添加免费车
     */
    @Override
    public void mfReserveData(DmPlateNumber dto) {
//        String url = "http://10.208.128.14:9999/api/park/addfreecar";
        JSONObject generateProcJson = new JSONObject();
        generateProcJson.put("name",dto.getUserNumber().getName());
        generateProcJson.put("phone",dto.getUserNumber().getContacts());
        generateProcJson.put("carplate",dto.getPlateNumber());
        SimpleDateFormat formater2 = new SimpleDateFormat("yyyy-MM-dd");
        generateProcJson.put("startdate",formater2.format(dto.getStartTime()));
        generateProcJson.put("enddate",formater2.format(dto.getEndTime()));
        generateProcJson.put("cardtype","A");
        if(StringUtils.equals(dto.getVehicleType(),"01")){
            generateProcJson.put("controllers", "1,2,3,4,5,6");
        } else if(StringUtils.equals(dto.getVehicleType(),"02")) {
            generateProcJson.put("controllers", "5,6");
        }

        String generateProcData = BeanMapUtils.doPostForm(mfUrl,generateProcJson);
        JSONObject generateProcDataJson = JSONObject.parseObject(generateProcData);
        System.out.println("免费车data"+generateProcJson);
        System.out.println("add免费车:"+generateProcDataJson);
    }

    @Override
    public DmPlateNumber findDmPlateNumberByTaskId(String taskId) {
        return dmPlateNumberRepository.findDmPlateNumberByTaskId(taskId);
    }

//    public JSONObject reserveMeetingData(DmPrintingRequest resources) throws IOException {
//        String url = "https://portal.caih.com/api-third-party/busi/comm/collaboration/process/generateProc";
//        JSONObject generateProcJson = new JSONObject();
//        JSONObject formData = new JSONObject();
//        formData.put("taskId",resources.getId());
//        generateProcJson.put("formData",formData);
//        User user = userRepository.getUserByDmUserId(resources.getRequestUser().getId());
//        JSONObject caihRuRequestInfo = new JSONObject();
//        if(!StringUtils.isBlank(user.getUserRootGroupId())&&!StringUtils.isBlank(user.getUserRootGroupName())) {
//            caihRuRequestInfo.put("compId", user.getUserRootGroupId());
//            caihRuRequestInfo.put("compName", user.getUserRootGroupName());
//        }
//        if(!StringUtils.isBlank(user.getDept().getId())&&!StringUtils.isBlank(user.getDept().getId())) {
//            caihRuRequestInfo.put("orgId", user.getDept().getId());
//            caihRuRequestInfo.put("orgName", user.getDept().getName());
//        }
//        caihRuRequestInfo.put("userId",user.getId());//user.getId()
//        caihRuRequestInfo.put("userName",user.getNickName());
//        caihRuRequestInfo.put("mobile",user.getPhone());//user.getPhone()
//        generateProcJson.put("caihRuRequestInfo",caihRuRequestInfo);
//        generateProcJson.put("procDefKey","CUST_e8d0cec5-2042-4730-a9ae-81bf4c2dd3e6");
//        generateProcJson.put("procName","办公-永天流程申请");
//        generateProcJson.put("tarTaskDefKey","taskDefinitionKey2");//taskId
//        generateProcJson.put("tenantId","caih");
//        System.out.println("xxx"+generateProcJson.toString());
//        String generateProcData = BeanMapUtils.sendPost(url,generateProcJson.toString());
//        JSONObject generateProcDataJson = JSONObject.parseObject(generateProcData);
//        System.out.println("generateProcDataJson:"+generateProcDataJson);
//        return generateProcDataJson;
//    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(DmPlateNumber resources) {
        DmPlateNumber dmPlateNumber = dmPlateNumberRepository.findById(resources.getId()).orElseGet(DmPlateNumber::new);
        ValidationUtil.isNull( dmPlateNumber.getId(),"DmPlateNumber","id",resources.getId());
        dmPlateNumber.copy(resources);
        dmPlateNumberRepository.save(dmPlateNumber);
    }

    @Override
    public void updateEnabled(String resources) {
        dmPlateNumberRepository.updateEnabled(resources);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            dmPlateNumberRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<DmPlateNumberDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (DmPlateNumberDto dmPlateNumber : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("用户", dmPlateNumber.getUserNumber().getName());
            map.put("车牌号", dmPlateNumber.getPlateNumber());
            map.put("有效开始时间", dmPlateNumber.getStartTime());
            map.put("有效结束时间", dmPlateNumber.getEndTime());
            map.put("效期状态(00-有效、01-过期)", dmPlateNumber.getEffectiveState());
            map.put("登记状态(00-待审核、01-已登记)", dmPlateNumber.getRegistrationStatus());
            map.put("创建者", dmPlateNumber.getCreateBy());
            map.put("更新者", dmPlateNumber.getUpdateBy());
            map.put("创建时间", dmPlateNumber.getCreateTime());
            map.put("更新时间", dmPlateNumber.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    /**
     * 多表查询
     */
    @Override
    public Map<String,Object> getAllPlateNumber(Pageable pageable){
        Page<DmPlateNumber> page = dmPlateNumberRepository.getAllPlateNumber(pageable);
        return PageUtil.toPage(page.map(dmPlateNumberMapper::toDto));
    }

    /* 搜索 */
    @Override
    public List<DmPlateNumberDto> findAllBysousuo(DmPlateNumber resources) {
        return dmPlateNumberMapper.toDto(dmPlateNumberRepository.findAllBysousuo(resources));
    }

    /* 根据一卡通卡号查询 */
    @Override
    public DmPlateNumber findDmPlateNumberByCardNumber(Long cardNumber) {
        return dmPlateNumberRepository.findDmPlateNumberByCardNumber(cardNumber);
    }

    @Override
    public String queryApprove() {
        return dmPlateNumberRepository.queryApprove();
    }

    @Override
    public void updateApprove(String isApprove) {
        dmPlateNumberRepository.updateApprove(isApprove);
    }

    @Override
    public DmPlateNumber findByUserId(String userId){
        return dmPlateNumberRepository.findByUserId(userId);
    }

//    @Override
//    public void getAllPlateNumber2(List<DmPlateNumberDto> all, HttpServletResponse response) throws IOException {
//        List<Map<String,Object>> list2 = new ArrayList<>();
//        for(DmPlateNumberDto dmPlateNumberDto : all){
//            Map<String, Object> map = new HashMap<String,Object>();
//            map.put("name",dmPlateNumberDto.getDmCardDto().getDmUserDto().getName());
//            map.put("userType",dmPlateNumberDto.getDmCardDto().getUserType());
//            map.put("cardNumber",dmPlateNumberDto.getDmCardDto().getCardNumber());
//            map.put("contacts",dmPlateNumberDto.getDmCardDto().getDmUserDto().getContacts());
//            map.put("plateNumber",dmPlateNumberDto.getPlateNumber());
//            map.put("startTime",dmPlateNumberDto.getStartTime());
//            map.put("endTime",dmPlateNumberDto.getEndTime());
//            map.put("effectiveState",dmPlateNumberDto.getEffectiveState());
//            map.put("registrationStatus",dmPlateNumberDto.getRegistrationStatus());
//            list2.add(map);
//        }
//        FileUtil.downloadExcel(list2, response);
//    }


}