package com.yunzhupaas.bsc.controller;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import com.yunzhupaas.base.ActionResult;
import com.yunzhupaas.base.UserInfo;
import com.yunzhupaas.exception.DataException;
import com.yunzhupaas.permission.entity.UserEntity;
import com.yunzhupaas.constant.MsgCode;
import com.yunzhupaas.bsc.service.*;
import com.yunzhupaas.bsc.entity.*;
import com.yunzhupaas.util.*;
import com.yunzhupaas.bsc.model.billingitem.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.yunzhupaas.flowable.entity.TaskEntity;
import jakarta.validation.Valid;
import java.util.*;
import com.yunzhupaas.model.ExcelModel;
import com.yunzhupaas.excel.ExcelExportStyler;
import com.yunzhupaas.excel.ExcelHelper;
import com.yunzhupaas.annotation.YunzhupaasField;
import com.yunzhupaas.base.vo.PageListVO;
import com.yunzhupaas.base.vo.PaginationVO;
import com.yunzhupaas.base.vo.DownloadVO;
import com.yunzhupaas.config.ConfigValueUtil;
import com.yunzhupaas.base.entity.ProvinceEntity;
import java.io.IOException;
import java.util.stream.Collectors;
import com.yunzhupaas.flowable.entity.TaskEntity;
import com.yunzhupaas.exception.WorkFlowException;
import com.yunzhupaas.model.visualJson.UploaderTemplateModel;
import com.yunzhupaas.base.util.FormExecelUtils;
import org.springframework.web.multipart.MultipartFile;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import com.yunzhupaas.onlinedev.model.ExcelImFieldModel;
import com.yunzhupaas.base.model.OnlineImport.ImportDataModel;
import com.yunzhupaas.base.model.OnlineImport.ImportFormCheckUniqueModel;
import com.yunzhupaas.base.model.OnlineImport.ExcelImportModel;
import com.yunzhupaas.base.model.OnlineImport.VisualImportModel;
import cn.xuyanwu.spring.file.storage.FileInfo;
import lombok.Cleanup;
import com.yunzhupaas.model.visualJson.config.HeaderModel;
import com.yunzhupaas.base.model.ColumnDataModel;
import com.yunzhupaas.base.util.VisualUtils;
import org.springframework.transaction.annotation.Transactional;

/**
 * 计费项目
 * @版本： V5.2.7
 * @版权： Copyright @ 2025  深圳市乐程软件有限公司版权所有
 * @作者： 深圳市乐程软件有限公司
 * @日期： 2026-05-20
 */
@Slf4j
@RestController
@Tag(name = "计费项目" , description = "1")
@RequestMapping("/api/bc/BillingItem")
public class BillingItemController {

    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private UserProvider userProvider;

    @Autowired
    private BillingItemService billingItemService;



    @Autowired
    private ConfigValueUtil configValueUtil;

    /**
    * 列表
    *
    * @param billingItemPagination
    * @return
    */
    @Operation(summary = "获取列表")
    @PostMapping("/getList")
    public ActionResult list(@RequestBody BillingItemPagination billingItemPagination)throws Exception{
        List<BillingItemEntity> list= billingItemService.getList(billingItemPagination);
        List<Map<String, Object>> realList=new ArrayList<>();
        for (BillingItemEntity entity : list) {
        Map<String, Object> billingItemMap=JsonUtil.entityToMap(entity);
        billingItemMap.put("id", billingItemMap.get("billing_item_id"));
        //副表数据
        //子表数据
            realList.add(billingItemMap);
        }
        //数据转换
        boolean isPc = "pc".equals(ServletUtil.getHeader("yunzhupaas-origin" ));
        realList = generaterSwapUtil.swapDataList(realList, BillingItemConstant.getFormData(), BillingItemConstant.getColumnData(), billingItemPagination.getModuleId(),isPc?false:false);

        //返回对象
        PageListVO vo = new PageListVO();
        vo.setList(realList);
        PaginationVO page = JsonUtil.getJsonToBean(billingItemPagination, PaginationVO.class);
        vo.setPagination(page);
        return ActionResult.success(vo);
    }
    /**
    * 创建
    *
    * @param billingItemForm
    * @return
    */
    @PostMapping()
    @Operation(summary = "创建")
    public ActionResult create(@RequestBody @Valid BillingItemForm billingItemForm) {
        String b = billingItemService.checkForm(billingItemForm,0);
        if (StringUtil.isNotEmpty(b)){
            return ActionResult.fail(b );
        }
        try{
            billingItemService.saveOrUpdate(billingItemForm, null ,true);
        }catch(Exception e){
            return ActionResult.fail(MsgCode.FA028.get());
        }
        return ActionResult.success(MsgCode.SU001.get());
    }
    /**
    * 导出Excel
    *
    * @return
    */
    @Operation(summary = "导出Excel")
    @PostMapping("/Actions/Export")
    public ActionResult Export(@RequestBody BillingItemPagination billingItemPagination) throws IOException {
        if (StringUtil.isEmpty(billingItemPagination.getSelectKey())){
            return ActionResult.fail(MsgCode.IMP011.get());
        }
        List<BillingItemEntity> list= billingItemService.getList(billingItemPagination);
        List<Map<String, Object>> realList=new ArrayList<>();
        for (BillingItemEntity entity : list) {
        Map<String, Object> billingItemMap=JsonUtil.entityToMap(entity);
        billingItemMap.put("id", billingItemMap.get("billing_item_id"));
        //副表数据
        //子表数据
            realList.add(billingItemMap);
        }
        //数据转换
        realList = generaterSwapUtil.swapDataList(realList, BillingItemConstant.getFormData(), BillingItemConstant.getColumnData(), billingItemPagination.getModuleId(),false);
        String[]keys=!StringUtil.isEmpty(billingItemPagination.getSelectKey())?billingItemPagination.getSelectKey():new String[0];
        UserInfo userInfo=userProvider.get();
        String menuFullName = generaterSwapUtil.getMenuName(billingItemPagination.getMenuId());

            DownloadVO vo=this.creatModelExcel(configValueUtil.getTemporaryFilePath(),realList,keys,userInfo,menuFullName);
        return ActionResult.success(vo);
    }

    /**
    * 导出表格方法
    */
    public DownloadVO creatModelExcel(String path,List<Map<String, Object>>list,String[]keys,UserInfo userInfo,String menuFullName){
        DownloadVO vo=DownloadVO.builder().build();
        List<ExcelExportEntity> entitys=new ArrayList<>();
        if(keys.length>0){
            for(String key:keys){
                switch(key){
                    case "billing_item_code" :
                    entitys.add(new ExcelExportEntity("计费项目编码" ,"billing_item_code"));
                    break;
                    case "billing_item_name" :
                    entitys.add(new ExcelExportEntity("计费项目名称" ,"billing_item_name"));
                    break;
                    case "billing_item_type" :
                    entitys.add(new ExcelExportEntity("费用类别" ,"billing_item_type"));
                    break;
                    case "remark" :
                    entitys.add(new ExcelExportEntity("备注" ,"remark"));
                    break;
                    default:
                    break;
                }
            }
        }

        ExportParams exportParams = new ExportParams(null, "表单信息");
        exportParams.setType(ExcelType.XSSF);
        try{
            @Cleanup Workbook workbook = new HSSFWorkbook();
            if (entitys.size()>0){
                if (list.size()==0){
                    list.add(new HashMap<>());
                }
                //去除空数据
                List<Map<String, Object>> dataList = new ArrayList<>();
                for (Map<String, Object> map : list) {
                    int i = 0;
                    for (String key : keys) {
                        //子表
                        if (key.toLowerCase().startsWith("tablefield")) {
                            String tableField = key.substring(0, key.indexOf("-" ));
                            String field = key.substring(key.indexOf("-" ) + 1);
                            Object o = map.get(tableField);
                            if (o != null) {
                                List<Map<String, Object>> childList = (List<Map<String, Object>>) o;
                                for (Map<String, Object> childMap : childList) {
                                    if (childMap.get(field) != null) {
                                        i++;
                                    }
                                }
                            }
                        } else {
                            Object o = map.get(key);
                            if (o != null) {
                                i++;
                            }
                        }
                    }
                    if (i > 0) {
                        dataList.add(map);
                    }
                }
                List<ExcelExportEntity> mergerEntitys = new ArrayList<>(entitys);
                List<Map<String, Object>> mergerList=new ArrayList<>(dataList);
                //复杂表头-表头和数据处理
                ColumnDataModel columnDataModel = JsonUtil.getJsonToBean(BillingItemConstant.getColumnData(), ColumnDataModel.class);
                List<HeaderModel> complexHeaderList = columnDataModel.getComplexHeaderList();
                if (!Objects.equals(columnDataModel.getType(), 3) && !Objects.equals(columnDataModel.getType(), 5)) {
                    entitys = VisualUtils.complexHeaderHandel(entitys, complexHeaderList, Objects.equals(columnDataModel.getType(), 4));
                    dataList =  VisualUtils.complexHeaderDataHandel(dataList, complexHeaderList, Objects.equals(columnDataModel.getType(), 4));
                }

                exportParams.setStyle(ExcelExportStyler.class);
                workbook = ExcelExportUtil.exportExcel(exportParams, entitys, dataList);
                VisualUtils.mergerVertical(workbook, mergerEntitys, mergerList);
                ExcelModel excelModel = generaterSwapUtil.getExcelParams(BillingItemConstant.getFormData(),Arrays.asList(keys));
                ExcelHelper helper = new ExcelHelper();
                helper.init(workbook, exportParams, entitys, excelModel);
                helper.doPreHandle();
                helper.doPostHandle();
            }
            String fileName = menuFullName  +"_"+ DateUtil.dateNow("yyyyMMddHHmmss") + ".xls";
            MultipartFile multipartFile = ExcelUtil.workbookToCommonsMultipartFile(workbook, fileName);
            String temporaryFilePath = configValueUtil.getTemporaryFilePath();
            FileInfo fileInfo = FileUploadUtils.uploadFile(multipartFile, temporaryFilePath, fileName);
            vo.setName(fileInfo.getFilename());
            vo.setUrl(UploaderUtil.uploaderFile(fileInfo.getFilename() + "#" + "Temporary") + "&name=" + fileName);
        } catch (Exception e) {
            log.error("信息导出Excel错误:{}", e.getMessage());
            e.printStackTrace();
        }
        return vo;
    }
    /**
    * 删除
    * @param id
    * @return
    */
    @Operation(summary = "删除")
    @DeleteMapping("/{id}")
    @Transactional
    public ActionResult delete(@PathVariable("id") String id,@RequestParam(name = "forceDel",defaultValue = "false") boolean forceDel) throws Exception{
        BillingItemEntity entity= billingItemService.getInfo(id);
        if(entity!=null){
            //主表数据删除
            billingItemService.delete(entity);
        }
        return ActionResult.success(MsgCode.SU003.get());
    }
    /**
    * 批量删除
    * @param obj
    * @return
    */
    @DeleteMapping("/batchRemove")
    @Transactional
    @Operation(summary = "批量删除")
    public ActionResult batchRemove(@RequestBody Object obj){
    Map<String, Object> objectMap = JsonUtil.entityToMap(obj);
    List<String> idList = JsonUtil.getJsonToList(objectMap.get("ids"), String.class);
    String errInfo = "";
    List<String> successList = new ArrayList<>();
        for (String allId : idList){
            try {
                this.delete(allId,false);
                successList.add(allId);
            } catch (Exception e) {
                errInfo = e.getMessage();
            }
        }
        if (successList.size() == 0 && StringUtil.isNotEmpty(errInfo)){
            return ActionResult.fail(errInfo);
        }
        return ActionResult.success(MsgCode.SU003.get());
    }
    /**
    * 编辑
    * @param id
    * @param billingItemForm
    * @return
    */
    @PutMapping("/{id}")
    @Operation(summary = "更新")
    public ActionResult update(@PathVariable("id") String id,@RequestBody @Valid BillingItemForm billingItemForm,
                                @RequestParam(value = "isImport", required = false) boolean isImport){
        BillingItemEntity entity= billingItemService.getInfo(id);
        if(entity!=null){
            billingItemForm.setBillingItemId(String.valueOf(entity.getBillingItemId()));

            if (!isImport) {
                String b =  billingItemService.checkForm(billingItemForm,1);
                if (StringUtil.isNotEmpty(b)){
                    return ActionResult.fail(b );
                }
            }

            try{
                billingItemService.saveOrUpdate(billingItemForm,id,false);
            }catch (DataException e1){
                return ActionResult.fail(e1.getMessage());
            }catch(Exception e){
                return ActionResult.fail(MsgCode.FA029.get());
            }
            return ActionResult.success(MsgCode.SU004.get());
        }else{
            return ActionResult.fail(MsgCode.FA002.get());
        }
    }
    /**
    * 表单信息(详情页)
    * 详情页面使用-转换数据
    * @param id
    * @return
    */
    @Operation(summary = "表单信息(详情页)")
    @GetMapping("/detail/{id}")
    public ActionResult detailInfo(@PathVariable("id") String id){
        BillingItemEntity entity= billingItemService.getInfo(id);
        if(entity==null){
            return ActionResult.fail(MsgCode.FA001.get());
        }
        Map<String, Object> billingItemMap=JsonUtil.entityToMap(entity);
        billingItemMap.put("id", billingItemMap.get("billing_item_id"));
        //副表数据
        //子表数据
        boolean isPc = "pc".equals(ServletUtil.getHeader("yunzhupaas-origin" ));
        billingItemMap = generaterSwapUtil.swapDataDetail(billingItemMap,BillingItemConstant.getFormData(),"823544899306521605",isPc?false:false);
        //子表数据
        return ActionResult.success(billingItemMap);
    }
    /**
    * 获取详情(编辑页)
    * 编辑页面使用-不转换数据
    * @param id
    * @return
    */
    @Operation(summary = "信息")
    @GetMapping("/{id}")
    public ActionResult info(@PathVariable("id") String id){
        BillingItemEntity entity= billingItemService.getInfo(id);
        if(entity==null){
            return ActionResult.fail(MsgCode.FA001.get());
        }
        Map<String, Object> billingItemMap=JsonUtil.entityToMap(entity);
        billingItemMap.put("id", billingItemMap.get("billing_item_id"));
        //副表数据
        //子表数据
        billingItemMap = generaterSwapUtil.swapDataForm(billingItemMap,BillingItemConstant.getFormData(),BillingItemConstant.TABLEFIELDKEY,BillingItemConstant.TABLERENAMES);
        return ActionResult.success(billingItemMap);
    }

}
