package com.engine.organization.service.impl;

import com.cloudstore.eccom.result.WeaResultMsg;
import com.engine.core.impl.Service;
import com.engine.organization.component.OrganizationWeaTable;
import com.engine.organization.entity.extend.bo.ExtendInfoBO;
import com.engine.organization.entity.extend.param.ExtendInfoParams;
import com.engine.organization.entity.extend.po.ExtendInfoPO;
import com.engine.organization.entity.personnelcard.po.CardAccessPO;
import com.engine.organization.entity.personnelcard.po.CardButtonPO;
import com.engine.organization.entity.personnelcard.vo.CardAccessVO;
import com.engine.organization.mapper.extend.ExtMapper;
import com.engine.organization.mapper.personnelcard.CardAccessMapper;
import com.engine.organization.mapper.personnelcard.CardButtonMapper;
import com.engine.organization.service.CardAccessService;
import com.engine.organization.transmethod.SystemTransMethod;
import com.engine.organization.util.HasRightUtil;
import com.engine.organization.util.db.MapperProxyFactory;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import weaver.general.Util;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @Author weaver_cl
 * @Description:
 * @Date 2022/11/1
 * @Version V1.0
 **/
public class CardAccessServiceImpl extends Service implements CardAccessService {

    private static final String RIGHT_NAME = "CardAccess:All";

    private CardAccessMapper getCardAccessMapper() {
        return MapperProxyFactory.getProxy(CardAccessMapper.class);
    }

    private CardButtonMapper getCardButtonMapper() {
        return MapperProxyFactory.getProxy(CardButtonMapper.class);
    }

    @Override
    public Map<String, Object> tablePage() {
        Map<String, Object> resultMap = new HashMap<>();
        OrganizationWeaTable<CardAccessVO> table = new OrganizationWeaTable<>(user, CardAccessVO.class);
        String sqlWhere = " where delete_type = 0";
        table.setSqlwhere(sqlWhere);
        WeaResultMsg result = new WeaResultMsg(false);
        result.putAll(table.makeDataResult());
        result.success();
        resultMap.putAll(result.getResultMap());

        return resultMap;
    }

    @Override
    public Map<String, Object> hasRight() {
        Map<String, Object> resultMap = new HashMap<>();
        boolean hasRight = HasRightUtil.hasRight(user, RIGHT_NAME, true);
        resultMap.put("hasRight", hasRight);
        return resultMap;
    }

    @Override
    public int save(Map<String, Object> params) {
        int rowNum = Util.getIntValue((String) params.get("rownum"));
        List<CardAccessPO> dataList = new ArrayList<>();
        for (int i = 0; i < rowNum; i++) {
            CardAccessPO data = CardAccessPO.builder()
                    .id(Util.getIntValue((String) params.get("id_" + i)))
                    .status(Util.getIntValue((String) params.get("status_" + i)))
                    .allPeople(Util.getIntValue((String) params.get("all_people_" + i)))
                    .superior(Util.getIntValue((String) params.get("superior_" + i)))
                    .allSuperior(Util.getIntValue((String) params.get("all_superior_" + i)))
                    .custom(Util.null2String(params.get("custom_" + i)))
                    .updateTime(new Date())
                    .build();
            dataList.add(data);
        }
        return getCardAccessMapper().saveCardAccess(dataList);
    }

    @Override
    public int deleteByIds(Collection<Long> ids) {
        return getCardAccessMapper().deleteByIds(ids);
    }

    @Override
    public int addData(CardAccessPO cardAccessPO) {
        return getCardAccessMapper().insertIgnoreNull(cardAccessPO);
    }

    @Override
    public int updateTabName(String name, Integer id) {
        return getCardAccessMapper().updateTabName(name, id);
    }

    @Override
    public Map<String, Object> getCardButtonTable() {
        List<ExtendInfoPO> infoPOList = new ArrayList<>();
        infoPOList.add(ExtendInfoPO.builder().id(null).fieldName("name").fieldNameDesc("按钮名称").fieldType("varchar(50)").controlType(1).browserType("1").customValue("[\"input\",\"text\",\"50\"]").showOrder(1).isrequired(0).isSystemDefault(0).build());
        infoPOList.add(ExtendInfoPO.builder().id(null).fieldName("status").fieldNameDesc("启用").fieldType("char(1)").controlType(7).browserType("1").customValue("[\"check\"]").showOrder(2).isrequired(0).isSystemDefault(0).build());
        infoPOList.add(ExtendInfoPO.builder().id(null).fieldName("url").fieldNameDesc("跳转地址").fieldType("varchar(1000)").controlType(1).browserType("1").customValue("[\"input\",\"text\",\"1000\"]").showOrder(3).isrequired(0).isSystemDefault(0).build());
        infoPOList.add(ExtendInfoPO.builder().id(null).fieldName("roles").fieldNameDesc("角色").fieldType("text").controlType(3).browserType("65").customValue("[\"browser\",{\"valueSpan\":\"多角色\",\"replaceDatas\":[{\"itemorderid\":\"65\",\"name\":\"多角色\",\"id\":\"65\",\"parenttitle\":\"人员\",\"title\":\"人员-多角色\"}],\"value\":\"65\"}]").showOrder(4).isrequired(0).isSystemDefault(0).build());

        Map<String, Object> tabInfoMap = new HashMap<>();
        tabInfoMap.put("columns", ExtendInfoBO.convertInfoListToTable(user, infoPOList, 2, false, true));
        List<CardButtonPO> cardButtonPOS = getCardButtonMapper().listAll();
        List<Integer> isUsed = new ArrayList<>();
        AtomicInteger index = new AtomicInteger(0);
        List<Map<String, Object>> collect = cardButtonPOS.stream().map(item -> {
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("id", item.getId());
            resultMap.put("name", item.getName());
            resultMap.put("status", "");
            resultMap.put("url", item.getUrl());
            resultMap.put("roles", item.getRoles());
            resultMap.put("rolesspan", SystemTransMethod.getRoleName(item.getRoles()));

            if (1 == item.getStatus()) {
                isUsed.add(index.get());
            }
            index.getAndIncrement();

            return resultMap;
        }).collect(Collectors.toList());

        tabInfoMap.put("datas", collect);
        tabInfoMap.put("api_status", true);
        Map<String, List<Integer>> isUsedMap = new HashMap<>();
        isUsedMap.put("status", isUsed);
        tabInfoMap.put("selectedData", isUsedMap);
        tabInfoMap.put("isModalEdit", false);

        return tabInfoMap;
    }

    @Override
    public int saveCardButton(Map<String, Object> params) {
        String tableName = "JCL_ORG_CARDBUTTON";
        int rowNum = Util.getIntValue((String) params.get("rownum"));
        int count = 0;
        List<Long> allIds = getCardButtonMapper().listAllId();
        for (int i = 0; i < rowNum; i++) {
            String recordIndex = "_" + i;
            Map<String, Object> recordData = new HashMap<>();
            recordData.put("name", params.get("name" + recordIndex));
            recordData.put("status", params.get("status" + recordIndex));
            recordData.put("url", params.get("url" + recordIndex));
            recordData.put("roles", params.get("roles" + recordIndex));
            // 排序字段
            recordData.put("show_order", i);
            // 预留字段
            // recordData.put("open", null);
            String id = Util.null2String(params.get("id" + recordIndex));
            if (StringUtils.isNotBlank(id)) {
                // 更新
                long buttonId = Long.parseLong(id);
                count += MapperProxyFactory.getProxy(ExtMapper.class).updateTable(ExtendInfoParams.builder().tableName(tableName).id(buttonId).params(recordData).build());
                allIds.remove(buttonId);
            } else {
                //插入
                recordData.put("sys_default", 1);
                recordData.put("delete_type", 0);
                count += MapperProxyFactory.getProxy(ExtMapper.class).insertTable(ExtendInfoParams.builder().tableName(tableName).params(recordData).build());
            }
        }
        if (CollectionUtils.isNotEmpty(allIds)) {
            count += getCardButtonMapper().deleteByIds(allIds);
        }
        return count;
    }


}
