package com.yeejoin.amos.boot.module.hygf.biz.controller;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.qiyuesuo.sdk.v2.bean.Contract;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.boot.module.hygf.api.entity.*;
import com.yeejoin.amos.boot.module.hygf.api.mapper.*;
import com.yeejoin.amos.boot.module.hygf.api.util.CommonResponseNewUtil;
import com.yeejoin.amos.boot.module.hygf.biz.service.impl.QiyuesuoServiceImpl;
import com.yeejoin.amos.boot.module.standard.api.entity.PublicAgencyUser;
import com.yeejoin.amos.boot.module.standard.api.mapper.PublicAgencyUserMapper;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.util.AesUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 农户信息
 *
 * @author system_generator
 * @date 2023-07-07
 */
@RestController
@Api(tags = "农户信息Api")
@RequestMapping(value = "/test")
@Slf4j
public class TestController extends BaseController {

    private static final String regionRedis = "app_region_redis";

    @Autowired
    UnitInfoMapper unitInfoMapper;

    @Autowired
    PublicAgencyUserMapper publicAgencyUserMapper;
    @Autowired
    PowerStationMapper powerStationMapper;
    @Autowired
    QiyuesuoServiceImpl qiyuesuoService;
    @Autowired
    HouseholdContractMapper householdContractMapper;
    @Autowired
    WorkOrderPowerStationMapper workOrderPowerStationMapper;
    @Autowired
    BasicGridRecordMapper basicGridRecordMapper;
    @Autowired
    AcceptanceCheckMapper acceptanceCheckMapper;
    @Autowired
    FinancingInfoMapper financingInfoMapper;


    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @GetMapping(value = "/initTime")
    @ApiOperation(httpMethod = "GET", value = "初始时间", notes = "初始时间")
    public ResponseModel<Object> initTime() {
        // 创建线程池
        ExecutorService executorService = Executors.newFixedThreadPool(5);

        // 提交不同的方法
        executorService.submit(this::dealKcTime);
        executorService.submit(this::dealDzhtqyTime);
        executorService.submit(this::dealSgTime);
        executorService.submit(this::dealBwTime);
        executorService.submit(this::dealYsTime);
        executorService.submit(this::dealTrTime);
        // 关闭线程池
        executorService.shutdown();
        return CommonResponseNewUtil.success();
    }

    private void dealTrTime() {
        log.info("================开始初始投融时间=========================");
        List<Map<String, Object>> trCreateTime = financingInfoMapper.getTrCreateTime();
        for (Map<String, Object> stringObjectMap : trCreateTime) {
            LambdaUpdateWrapper<FinancingInfo> wrapper = new LambdaUpdateWrapper<>();
            wrapper.set(FinancingInfo::getTrCreateTime, stringObjectMap.get("time"))
                    .eq(FinancingInfo::getSequenceNbr, stringObjectMap.get("sequenceNbr"));
            financingInfoMapper.update(null, wrapper);
        }
        List<Map<String, Object>> trEndTime = financingInfoMapper.getTrEndTime();
        for (Map<String, Object> stringObjectMap : trEndTime) {
            LambdaUpdateWrapper<FinancingInfo> wrapper = new LambdaUpdateWrapper<>();
            wrapper.set(FinancingInfo::getTrEndTime, stringObjectMap.get("time"))
                    .eq(FinancingInfo::getSequenceNbr, stringObjectMap.get("sequenceNbr"));
            financingInfoMapper.update(null, wrapper);
        }
        log.info("================投融时间更新完成=========================");
    }

    private void dealYsTime() {
        log.info("================开始初始验收时间=========================");
        List<Map<String, Object>> ysCreateTime = acceptanceCheckMapper.getYsCreateTime();
        for (Map<String, Object> stringObjectMap : ysCreateTime) {
            LambdaUpdateWrapper<AcceptanceCheck> wrapper = new LambdaUpdateWrapper<>();
            wrapper.set(AcceptanceCheck::getYsCreateTime, stringObjectMap.get("time"))
                    .eq(AcceptanceCheck::getPeasantHouseholdId, stringObjectMap.get("peasantHouseholdId"));
            acceptanceCheckMapper.update(null, wrapper);
        }
        List<Map<String, Object>> ysEndTime = acceptanceCheckMapper.getYsEndTime();
        for (Map<String, Object> stringObjectMap : ysEndTime) {
            LambdaUpdateWrapper<AcceptanceCheck> wrapper = new LambdaUpdateWrapper<>();
            wrapper.set(AcceptanceCheck::getYsEndTime, stringObjectMap.get("time"))
                    .eq(AcceptanceCheck::getSequenceNbr, stringObjectMap.get("sequenceNbr"));
            acceptanceCheckMapper.update(null, wrapper);
        }
        log.info("================验收时间更新完成=========================");
    }

    private void dealBwTime() {
        log.info("================开始初始并网时间=========================");
        List<Map<String, Object>> bwCreateTime = basicGridRecordMapper.getBwCreateTime();
        for (Map<String, Object> stringObjectMap : bwCreateTime) {
            LambdaUpdateWrapper<BasicGridRecord> wrapper = new LambdaUpdateWrapper<>();
            wrapper.set(BasicGridRecord::getBwCreateTime, stringObjectMap.get("time"))
                    .eq(BasicGridRecord::getPeasantHouseholdId, stringObjectMap.get("peasantHouseholdId"));
            basicGridRecordMapper.update(null, wrapper);
        }
        List<Map<String, Object>> bwEndTime = basicGridRecordMapper.getBwEndTime();
        for (Map<String, Object> stringObjectMap : bwEndTime) {
            LambdaUpdateWrapper<BasicGridRecord> wrapper = new LambdaUpdateWrapper<>();
            wrapper.set(BasicGridRecord::getBwEndTime, stringObjectMap.get("time"))
                    .eq(BasicGridRecord::getSequenceNbr, stringObjectMap.get("sequenceNbr"));
            basicGridRecordMapper.update(null, wrapper);
        }
        log.info("================并网时间更新完成=========================");
    }

    private void dealSgTime() {
        log.info("================开始初始施工时间=========================");
        List<Map<String, Object>> sgCreateTime = workOrderPowerStationMapper.getSgCreateTime();
        for (Map<String, Object> stringObjectMap : sgCreateTime) {
            LambdaUpdateWrapper<WorkOrderPowerStation> wrapper = new LambdaUpdateWrapper<>();
            wrapper.set(WorkOrderPowerStation::getSgCreateTime, stringObjectMap.get("time"))
                    .eq(WorkOrderPowerStation::getSequenceNbr, stringObjectMap.get("workOrderPowerStationId"));
            workOrderPowerStationMapper.update(null, wrapper);
        }
        List<Map<String, Object>> sgEndTime = workOrderPowerStationMapper.getSgEndTime();
        for (Map<String, Object> stringObjectMap : sgEndTime) {
            LambdaUpdateWrapper<WorkOrderPowerStation> wrapper = new LambdaUpdateWrapper<>();
            wrapper.set(WorkOrderPowerStation::getSgEndTime, stringObjectMap.get("time"))
                    .eq(WorkOrderPowerStation::getSequenceNbr, stringObjectMap.get("sequenceNbr"));
            workOrderPowerStationMapper.update(null, wrapper);
        }
        log.info("================施工时间更新完成=========================");
    }

    private void dealSjTime() {
        log.info("================开始初始设计时间=========================");
        List<Map<String, Object>> sjCreateTime = powerStationMapper.getSjCreateTime();
        for (Map<String, Object> stringObjectMap : sjCreateTime) {
            LambdaUpdateWrapper<PowerStation> wrapper = new LambdaUpdateWrapper<>();
            wrapper.set(PowerStation::getSjCreateTime, dealHour(stringObjectMap.get("time")))
                    .eq(PowerStation::getProcessInstanceId, stringObjectMap.get("processInstanceId"));
            powerStationMapper.update(null, wrapper);
        }
        List<Map<String, Object>> sjEndTime = powerStationMapper.getSjEndTime();
        for (Map<String, Object> stringObjectMap : sjEndTime) {
            LambdaUpdateWrapper<PowerStation> wrapper = new LambdaUpdateWrapper<>();
            wrapper.set(PowerStation::getSjEndTime, dealHour(stringObjectMap.get("time")))
                    .eq(PowerStation::getProcessInstanceId, stringObjectMap.get("processInstanceId"));
            powerStationMapper.update(null, wrapper);
        }
        log.info("================设计时间更新完成=========================");
    }

    private void dealDzhtqyTime() {
        log.info("================开始初始电子合同时间=========================");
        Map<Long, Contract> contractMap = qiyuesuoService.getContractMap();
        contractMap.forEach((k, v) -> {
            LambdaUpdateWrapper<HouseholdContract> wrapper = new LambdaUpdateWrapper<>();
            wrapper.set(HouseholdContract::getDzhtqyCreateTime, DateUtils.dateParse(v.getPublishTime()))
                    .eq(HouseholdContract::getContractLockId, k);
            householdContractMapper.update(null, wrapper);
        });
        List<Map<String, Object>> dzhtqyEndTime = householdContractMapper.getDzhtqyEndTime();
        for (Map<String, Object> stringObjectMap : dzhtqyEndTime) {
            LambdaUpdateWrapper<HouseholdContract> wrapper = new LambdaUpdateWrapper<>();
            wrapper.set(HouseholdContract::getSigningTime, stringObjectMap.get("time"))
                    .eq(HouseholdContract::getSequenceNbr, stringObjectMap.get("sequenceNbr"));
            householdContractMapper.update(null, wrapper);
        }
        log.info("================电子合同时间更新完成=========================");
    }

    private Date dealHour(Object dateString) {
        if (Objects.isNull(dateString)) {
            return null;
        }
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
            // 转换为 LocalDateTime
//        LocalDateTime localDateTime = LocalDateTime.parse(String.valueOf(dateString));
            // 转换为 Date
            Date date = null;

            date = format.parse(String.valueOf(dateString));

            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);

            // 加8小时
            calendar.add(Calendar.HOUR_OF_DAY, 8);
            return calendar.getTime();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private void dealKcTime() {
        log.info("================开始初始勘察时间=========================");
        List<Map<String, Object>> kcCreateTime = powerStationMapper.getKcCreateTime();
        for (Map<String, Object> stringObjectMap : kcCreateTime) {
            LambdaUpdateWrapper<PowerStation> wrapper = new LambdaUpdateWrapper<>();
            wrapper.set(PowerStation::getKcCreateTime, dealHour(stringObjectMap.get("time")))
                    .eq(PowerStation::getProcessInstanceId, stringObjectMap.get("processInstanceId"));
            powerStationMapper.update(null, wrapper);
        }
        List<Map<String, Object>> kcEndTime = powerStationMapper.getKcEndTime();
        for (Map<String, Object> stringObjectMap : kcEndTime) {
            LambdaUpdateWrapper<PowerStation> wrapper = new LambdaUpdateWrapper<>();
            wrapper.set(PowerStation::getKcEndTime, dealHour(stringObjectMap.get("time")))
                    .eq(PowerStation::getProcessInstanceId, stringObjectMap.get("processInstanceId"));
            powerStationMapper.update(null, wrapper);
        }
        log.info("================勘察时间更新完成=========================");
        dealSjTime();
    }

    /**
     * 新增农户信息
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @GetMapping(value = "/initpw")
    @ApiOperation(httpMethod = "GET", value = "新增农户信息", notes = "新增农户信息")
    public ResponseModel<Object> initpw() {
        // 经销商管理员
        List<UnitInfo> list = unitInfoMapper.selectList(null);
        for (UnitInfo unitInfo : list) {
            try {
                int ph = unitInfo.getAdminPhone().length();
                String npwd = "Zxnk_" + unitInfo.getAdminPhone().substring(ph - 4, ph);
                String npwdm = AesUtil.encode(npwd, "qaz");
                unitInfo.setAdminLoginPwd(npwdm);
                FeignClientResult<AgencyUserModel> re = Privilege.agencyUserClient
                        .queryByUserId(unitInfo.getAdminUserId());
                AgencyUserModel ag = re.getResult();
                ag.setPassword(AesUtil.encode(npwd, "qaz"));
                ag.setRePassword(AesUtil.encode(npwd, "qaz"));
                Privilege.agencyUserClient.restorePassword(unitInfo.getAdminUserId());
                ag.setOriginalPassword(AesUtil.encode("Z2%Op9.q", "qaz"));
                Privilege.agencyUserClient.modifyPassword(unitInfo.getAdminUserId(), ag);
                unitInfoMapper.updateById(unitInfo);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // 经销商子人员
        List<PublicAgencyUser> list2 = publicAgencyUserMapper.selectList(null);
        for (PublicAgencyUser unitInfo : list2) {
            try {
                int ph = unitInfo.getEmergencyTelephone().length();
                String npwd = "Zxnk_" + unitInfo.getEmergencyTelephone().substring(ph - 4, ph);
                String npwdm = AesUtil.encode(npwd, "qaz");
                unitInfo.setPassword(npwdm);
                FeignClientResult<AgencyUserModel> re = Privilege.agencyUserClient
                        .queryByUserId(unitInfo.getAmosUserId());
                AgencyUserModel ag = re.getResult();
                ag.setPassword(AesUtil.encode(npwd, "qaz"));
                ag.setRePassword(AesUtil.encode(npwd, "qaz"));
                Privilege.agencyUserClient.restorePassword(unitInfo.getAmosUserId());
                ag.setOriginalPassword(AesUtil.encode("Z2%Op9.q", "qaz"));
                Privilege.agencyUserClient.modifyPassword(unitInfo.getAmosUserId(), ag);
                publicAgencyUserMapper.updateById(unitInfo);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return CommonResponseNewUtil.success();
    }
}