package com.yeejoin.amos.boot.module.hygf.biz.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.hygf.api.Enum.RectificationStatusEnum;
import com.yeejoin.amos.boot.module.hygf.api.dto.AcceptanceRectificationOrderDto;
import com.yeejoin.amos.boot.module.hygf.api.dto.FileItemDto;
import com.yeejoin.amos.boot.module.hygf.api.dto.StandardDto;
import com.yeejoin.amos.boot.module.hygf.api.entity.AcceptanceRectificationOrder;
import com.yeejoin.amos.boot.module.hygf.api.entity.BasicGridAcceptance;
import com.yeejoin.amos.boot.module.hygf.api.mapper.AcceptanceRectificationOrderMapper;
import com.yeejoin.amos.boot.module.hygf.api.mapper.BasicGridAcceptanceMapper;
import com.yeejoin.amos.boot.module.hygf.api.service.IAcceptanceRectificationOrderService;
import com.yeejoin.amos.boot.module.hygf.api.util.RedisLockUtil;
import com.yeejoin.amos.component.robot.BadRequest;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.rdbms.service.BaseService;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 验收整改单服务实现类
 *
 * @author system_generator
 * @date 2024-01-16
 */
@Service
public class AcceptanceRectificationOrderServiceImpl extends BaseService<AcceptanceRectificationOrderDto, AcceptanceRectificationOrder, AcceptanceRectificationOrderMapper> implements IAcceptanceRectificationOrderService {
    @Autowired
    private AcceptanceRectificationOrderMapper acceptanceRectificationOrderMapper;
//    @Value("${hygf.role.gc.roleSeq}")
//    private String hygfGcRoleSeq;
    @Autowired
    private BasicGridAcceptanceMapper basicGridAcceptanceMapper;
    @Autowired
    private WorkflowImpl workflow;
    @Autowired
    private RedisUtils redisUtils;
    @Resource (type = RedisLockUtil.class)
    private RedisLockUtil redisLockUtil;
    /**
     * 分页查询
     */
    public Page<AcceptanceRectificationOrderDto> queryForAcceptanceRectificationOrderPage(Page<AcceptanceRectificationOrderDto> page, Long acceptanceSeqNbr) {
        return acceptanceRectificationOrderMapper.page(page, acceptanceSeqNbr);
    }

    
    /**
     * 列表查询 示例
     */
    public List<AcceptanceRectificationOrderDto> queryForAcceptanceRectificationOrderList() {
        return this.queryForList("", false);
    }

    public AcceptanceRectificationOrderDto queryBySequenceNbr(Long sequenceNbr) {
        AcceptanceRectificationOrderDto dto = acceptanceRectificationOrderMapper.queryBySequenceNbr(sequenceNbr);
        if (StringUtils.isNotEmpty(dto.getRectificationPhotoStr())) {
            JSONArray jsonArray = JSONArray.parseArray(dto.getRectificationPhotoStr());
            List<FileItemDto> itemDtos = new ArrayList<>();
            for (Object obj : jsonArray) {
                String jsonString = JSONObject.toJSONString(obj);
                FileItemDto itemDto = JSONObject.parseObject(jsonString, FileItemDto.class);
                itemDtos.add(itemDto);
            }
            dto.setRectificationPhoto(itemDtos);
        }
        return dto;
    }

    /**
     * 查询负责人列表(经销商工程角色)
     */
    public List<AgencyUserModel> queryDirectors(Long companyId) {
//        try {
//            //FeignClientResult<List<AgencyUserModel>> response = Privilege.agencyUserClient.queryByCompanyRoles(companyId, hygfGcRoleSeq, null, "UNLOCK");
//            if (response.getStatus() == 200) {
//                return response.getResult();
//            } else {
//                throw new RuntimeException(response.getMessage());
//            }
//        } catch (RuntimeException e) {
//            throw new RuntimeException(e.getMessage());
//        }
        return null;
    }

    /**
     * 提交整改并触发工作流
     */

    @GlobalTransactional
    public AcceptanceRectificationOrderDto updateAndDriveWorkflow(AcceptanceRectificationOrderDto model, String userId) {
        ReginParams reginParams = JSONObject.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);

        // 提交整改信息
        AcceptanceRectificationOrder entity = new AcceptanceRectificationOrder();
        BeanUtils.copyProperties(model, entity);

        String lockName = String.format("LockName:updateAndDriveWorkflow:%s", entity.getSequenceNbr());
        Boolean isLocked = redisLockUtil.tryLock(lockName, lockName, 10, 1);
        if (BooleanUtils.isNotTrue(isLocked)) {
            throw new BadRequest("其他用户正在操作，请刷新后再试！");
        }
        try {

            AcceptanceRectificationOrder acceptanceRectificationOrder = acceptanceRectificationOrderMapper.selectById(entity.getSequenceNbr());
            if (String.valueOf(RectificationStatusEnum.整改已完成.getCode()).equals(acceptanceRectificationOrder.getRectificationStatus())) {
                throw new BadRequest("整改已完成，请稍后再试！");
            }

            acceptanceRectificationOrderMapper.updateById(entity);

            // 如果整改已完成则触发工作流
            String status = entity.getRectificationStatus();
            if (String.valueOf(RectificationStatusEnum.整改已完成.getCode()).equals(status)) {
                BasicGridAcceptance basicGridAcceptance = basicGridAcceptanceMapper.selectOne(
                        Wrappers.<BasicGridAcceptance>lambdaQuery()
                                .eq(BasicGridAcceptance::getPeasantHouseholdId, entity.getPeasantHouseholdId())
                );

                basicGridAcceptance.setAcceptanceStatus(String.valueOf(Integer.parseInt(basicGridAcceptance.getAcceptanceStatus()) - 1));

                StandardDto standardDto=new StandardDto();
                standardDto.setTaskId(basicGridAcceptance.getNextTaskId());
                workflow.standard(basicGridAcceptance,standardDto,userId);

                basicGridAcceptanceMapper.updateById(basicGridAcceptance);
            }
        } finally {
            redisLockUtil.releaseLock(lockName);
        }
        return model;
    }
}

