package com.gxwebsoft.cms.controller;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.cms.service.CmsAppFieldService;
import com.gxwebsoft.cms.entity.CmsAppField;
import com.gxwebsoft.cms.param.CmsAppFieldParam;
import com.gxwebsoft.cms.param.CmsAppFieldImportParam;
import com.gxwebsoft.common.core.utils.JSONUtil;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.core.web.BatchParam;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.checkerframework.checker.units.qual.A;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * 应用参数控制器
 *
 * @author 科技小王子
 * @since 2024-09-10 20:36:14
 */
@Tag(name = "应用参数管理")
@RestController
@RequestMapping("/api/cms/cms-app-field")
public class CmsAppFieldController extends BaseController {
    @Resource
    private CmsAppFieldService cmsAppFieldService;

    @Operation(summary = "分页查询应用参数")
    @GetMapping("/page")
    public ApiResult<PageResult<CmsAppField>> page(CmsAppFieldParam param) {
        // 使用关联查询
        return success(cmsAppFieldService.pageRel(param));
    }

    @Operation(summary = "查询全部应用参数")
    @GetMapping()
    public ApiResult<List<CmsAppField>> list(CmsAppFieldParam param) {
        // 使用关联查询
        return success(cmsAppFieldService.listRel(param));
    }

    @Operation(summary = "根据id查询应用参数")
    @GetMapping("/{id}")
    public ApiResult<CmsAppField> get(@PathVariable("id") Integer id) {
        // 使用关联查询
        return success(cmsAppFieldService.getByIdRel(id));
    }

    @Operation(summary = "根据code查询应用参数")
    @GetMapping("/getByCode/{code}")
    public ApiResult<CmsAppField> getByCode(@PathVariable("code") String code) {
        // 使用关联查询
        return success(cmsAppFieldService.getByCodeRel(code));
    }

    @PreAuthorize("hasAuthority('cms:cmsAppField:save')")
    @Operation(summary = "添加应用参数")
    @PostMapping()
    public ApiResult<?> save(@RequestBody CmsAppField cmsAppField) {
        if (cmsAppFieldService.save(cmsAppField)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('cms:cmsAppField:update')")
    @Operation(summary = "修改应用参数")
    @PutMapping()
    public ApiResult<?> update(@RequestBody CmsAppField cmsAppField) {
        if (cmsAppFieldService.updateById(cmsAppField)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('cms:cmsAppField:remove')")
    @Operation(summary = "删除应用参数")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (cmsAppFieldService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @PreAuthorize("hasAuthority('cms:cmsAppField:save')")
    @Operation(summary = "批量添加应用参数")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<CmsAppField> list) {
        if (cmsAppFieldService.saveBatch(list)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('cms:cmsAppField:update')")
    @Operation(summary = "批量修改应用参数")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<CmsAppField> batchParam) {
        if (batchParam.update(cmsAppFieldService, "id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('cms:cmsAppField:remove')")
    @Operation(summary = "批量删除应用参数")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        if (cmsAppFieldService.removeByIds(ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @Operation(summary = "获取网站配置参数-对象形式")
    @GetMapping("/config")
    public ApiResult<?> getConfig(CmsAppFieldParam param) {
      // 使用关联查询
      final List<CmsAppField> fields = cmsAppFieldService.listRel(param);

      HashMap<String, Object> config = new HashMap<>();
      fields.forEach(d -> {
        config.put(d.getName(), d.getValue());
      });
      return success(config);
    }

    /**
     * excel批量导入应用参数
     */
    @PreAuthorize("hasAuthority('cms:cmsAppField:save')")
    @Operation(summary = "批量导入应用参数")
    @Transactional(rollbackFor = {Exception.class})
    @PostMapping("/import")
    public ApiResult<List<String>> importBatch(MultipartFile file) {
        ImportParams importParams = new ImportParams();
        try {
            // 第一步：永久删除已标记为 deleted=1 的记录
            cmsAppFieldService.remove(new LambdaQueryWrapper<CmsAppField>().eq(CmsAppField::getDeleted, 1));

            // 第二步：将现有未删除的记录（deleted=0）标记为 deleted=1
            LambdaUpdateWrapper<CmsAppField> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(CmsAppField::getDeleted, 0);
            updateWrapper.set(CmsAppField::getDeleted, 1);
            cmsAppFieldService.update(updateWrapper);

            // 第三步：导入XLS文件的内容
            List<CmsAppFieldImportParam> list = ExcelImportUtil.importExcel(file.getInputStream(), CmsAppFieldImportParam.class, importParams);
            list.forEach(d -> {
                CmsAppField item = JSONUtil.parseObject(JSONUtil.toJSONString(d), CmsAppField.class);
                assert item != null;
                if (ObjectUtil.isNotEmpty(item)) {
                  System.out.println("item = " + item);
                    // 设置默认值
                    if (item.getDeleted() == null) {
                        item.setDeleted(0); // 新导入的数据deleted设为0
                    }
                    if (item.getSortNumber() == null) {
                        item.setSortNumber(100);
                    }
                    if (item.getEncrypted() == null) {
                        item.setEncrypted(false);
                    }
                    cmsAppFieldService.save(item);
                }
            });
            return success("成功导入" + list.size() + "条", null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fail("导入失败", null);
    }
}
