package org.jeecg.ctop.finance.settlement.service.serviceImpl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.com.ctop.alarm.modules.entity.RuleAccountTemplate;
import cn.com.ctop.alarm.modules.service.impl.RuleAccountTemplateServiceImpl;
import cn.com.ctop.common.module.entity.SysLog;
import cn.com.ctop.common.module.entity.UserAllocation;
import cn.com.ctop.common.module.mapper.SysLogMapper;
import cn.com.ctop.common.module.mapper.SysUserMapper;
import cn.com.ctop.common.module.service.impl.UserAllocationServiceImpl;
import cn.com.ctop.common.module.utils.Check;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.lettuce.core.dynamic.annotation.Param;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.entity.SysUser;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.ctop.finance.policy.entity.CwjsCompanySubject;
import org.jeecg.ctop.finance.policy.entity.CwjsPolicyInfo;
import org.jeecg.ctop.finance.policy.entity.CwjsPolicyProduct;
import org.jeecg.ctop.finance.policy.mapper.CwjsCompanySubjectMapper;
import org.jeecg.ctop.finance.policy.mapper.CwjsPolicyInfoMapper;
import org.jeecg.ctop.finance.policy.mapper.CwjsPolicyProductMapper;
import org.jeecg.ctop.finance.policy.service.impl.CwjsPolicyProductServiceImpl;
import org.jeecg.ctop.finance.settlement.entity.pojo.CtopCwjsSettlementInfo;
import org.jeecg.ctop.finance.settlement.entity.vo.AccountImportVo;
import org.jeecg.ctop.finance.settlement.entity.vo.PolicyImportVo;
import org.jeecg.ctop.finance.settlement.mapper.SettlementInfoMapper;
import org.jeecg.ctop.finance.settlement.service.ISettlementInfoService;
import org.jeecg.modules.ctop.entity.ProjectMember;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


@Slf4j
@Service
public class SettlementInfoServiceImpl extends ServiceImpl<SettlementInfoMapper, CtopCwjsSettlementInfo> implements ISettlementInfoService {

    @Resource
    private SettlementInfoMapper settlementInfoMapper;


    @Resource
    SysLogMapper sysLogMapper;


    /**
     * @param settlementInfo
     * @param pageNo
     * @param pageSize
     * @description: 查询 财务结算-账户列表
     * @return: org.jeecg.common.api.vo.Result
     * @author: zianY
     */
    @Override
    public Result getSettlementList(CtopCwjsSettlementInfo settlementInfo, Integer pageNo, Integer pageSize) {
        PageHelper.startPage(pageNo, pageSize);
        List<CtopCwjsSettlementInfo> list = settlementInfoMapper.getSettlementList(settlementInfo);
        PageInfo<CtopCwjsSettlementInfo> pageInfo = new PageInfo<>(list);
        return Result.successMsg("财务结算-账户列表查询成功", pageInfo);
    }


    @Autowired
    private UserAllocationServiceImpl userAllocationService;

    /**
     * @param id
     * @param status 账户状态 0-开 1-关
     * @description: 财务结算-修改账户状态
     * @return: org.jeecg.common.api.vo.Result
     * @author: zianY
     */
    @Override
    public Result updSettlementStatusById(Long id, Integer status) {
        // 修改状态
        settlementInfoMapper.updSettlementStatusById(id, status);

        //同步 状态
        CtopCwjsSettlementInfo settlementInfo = settlementInfoMapper.selectById(id);

        UserAllocation userAllocation = userAllocationService.getByAccountId(new Long(settlementInfo.getAccountId()));
        if (!Check.isNull(userAllocation)) {
            userAllocation.setAccountStatus(status);
            userAllocationService.editUserAlloCation(userAllocation);
        } else {
            LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            SysLog sysLog = new SysLog();
            sysLog.setLogType(2);
            sysLog.setLogContent(String.valueOf(status));
            sysLog.setRequestParam(userAllocation.getAccountId().toString());
            sysLog.setOperateType(10001);
            sysLog.setUserid(user.getId());
            sysLog.setCreateBy(user.getRealname());
            sysLog.setCreateTime(new Date());
            sysLogMapper.insert(sysLog);
        }

        return Result.successMsg("财务结算-修改账户状态成功", null);
    }


/*
    public Result<UserAllocation> edit(UserAllocation userAllocation) {
        Result<UserAllocation> result = new Result<>();
        UserAllocation userAllocationEntity = userAllocationService.getById(userAllocation.getId());
        if (userAllocationEntity == null) {
            result.error500("未找到对应实体");
        } else {
            boolean ok = userAllocationService.updateById(userAllocation);
            Integer accountStatus = userAllocation.getAccountStatus();
            if (!Check.isNull(accountStatus)) {
                if (accountStatus == 1) {
                    QueryWrapper<RuleAccountTemplate> ruleAccountTemplateQueryWrapper = new QueryWrapper<>();
                    ruleAccountTemplateQueryWrapper.eq("account_id", userAllocationEntity.getAccountId());
                    RuleAccountTemplate updateRuleAccountTemplate = new RuleAccountTemplate();
                    updateRuleAccountTemplate.setTemplateStatus(1);
                    ruleAccountTemplateService.update(updateRuleAccountTemplate, ruleAccountTemplateQueryWrapper);
                }
            }

            UserAllocation update = userAllocationService.getById(userAllocation.getId());
            QueryWrapper<ProjectMember> memberQueryWrapper = new QueryWrapper<>();
            memberQueryWrapper.eq("user_id", update.getUserId());
            memberQueryWrapper.eq("project_id", update.getProjectId());
            memberQueryWrapper.last("limit 1");
            ProjectMember member = memberMapper.selectOne(memberQueryWrapper);
            if (Check.isNull(member)) {
                ProjectMember addMember = new ProjectMember();
                addMember.setProjectId(userAllocationEntity.getProjectId());
                addMember.setUserId(userAllocationEntity.getUserId());
                addMember.setUserName(userAllocationEntity.getUserName());
                String roleCode = sysRoleService.getRoleCodeByUserId(userAllocationEntity.getUserId());
                if (!Check.isNull(roleCode)) {
                    addMember.setRoleCode(roleCode);
                }
                projectMemberService.save(addMember);
            }

            if (ok) {
                result.success("修改成功!");
            }
        }
        return result;
    }
    */

    /**
     * @param id
     * @description: 删除
     * @return: org.jeecg.common.api.vo.Result
     * @author: zianY
     */
    @Override
    public Result deleteSettlementById(Long id) {
        settlementInfoMapper.deleteSettlementById(id);
        return Result.successMsg("财务结算-删除成功", null);
    }


    /**
     * @param settlementInfo
     * @param file
     * @description:
     * @return: org.jeecg.common.api.vo.Result
     * @author: zianY
     * @time: 2021/7/30 16:26
     */
    @Override
    public Result settlementAccountImport(CtopCwjsSettlementInfo settlementInfo, MultipartFile file) {

        try {
            //LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            //settlementInfo.setCreateUserId(user.getId());
            //settlementInfo.setCreateUserId("b161b7d9793942f980dbfe8c931cd1b0");
            ImportParams importParams = new ImportParams();
            //表格标题行数
            importParams.setTitleRows(1);
            //表头行数
            importParams.setHeadRows(1);

            //校验表头 头条
            if (StringUtils.equals("1", String.valueOf(settlementInfo.getMediaId()))) {
                importParams.setImportFields(new String[]{"账户ID", "账户名称"});
                //快手
            } else if (StringUtils.equals("2", String.valueOf(settlementInfo.getMediaId()))) {
                importParams.setImportFields(new String[]{"快手ID", "账户ID", "账户名称"});
            }
            //校验excel的标题列顺序
            importParams.setNeedCheckOrder(true);
            ExcelImportResult<AccountImportVo> importResult = ExcelImportUtil.importExcelMore(file.getInputStream(), AccountImportVo.class, importParams);
            if (importResult.getList().size() < 1) {
                return Result.error("读取Excel失败，数据不能为空，请重新检查数据并导入");
            }
            for (AccountImportVo importVo : importResult.getList()) {
                if (Check.isNull(importVo.getAccountId())) {
                    continue;
                }
                //查询 账户 状态
                UserAllocation userAllocation = userAllocationService.getByAccountId(new Long(importVo.getAccountId()));
                if (Check.isNull(userAllocation)) {
                    settlementInfo.setStatus(0);
                } else {
                    settlementInfo.setStatus(userAllocation.getAccountStatus());
                }
                BeanUtils.copyProperties(importVo, settlementInfo);
                //根据账户id 查看
                CtopCwjsSettlementInfo cwjs = settlementInfoMapper.getSettlementByAccountId(importVo.getAccountId());
                if (Check.isNull(cwjs)) {
                    // BeanUtils.copyProperties(importVo,settlementInfo);
                    settlementInfoMapper.insert(settlementInfo);
                } else {
                    settlementInfo.setId(cwjs.getId());
                    settlementInfoMapper.updateById(settlementInfo);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("账户数据上传失败，请使用正确的模板导入！");
        }
        return Result.successMsg("账户数据上传成功", null);
    }


    /**
     * @param userIds
     * @description: 查询多个用户信息
     * @return: java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     * @author: zianY
     */
    @Override
    public List<Map<String, Object>> getUserByIds(Set userIds) {
        return settlementInfoMapper.getUserByIds(userIds);
    }

}
