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.CmsWebsiteFieldService;
import com.gxwebsoft.cms.entity.CmsWebsiteField;
import com.gxwebsoft.cms.param.CmsWebsiteFieldParam;
import com.gxwebsoft.cms.param.CmsWebsiteFieldImportParam;
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-website-field")
public class CmsWebsiteFieldController extends BaseController {
    @Resource
    private CmsWebsiteFieldService cmsWebsiteFieldService;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            // 第三步：导入XLS文件的内容
            List<CmsWebsiteFieldImportParam> list = ExcelImportUtil.importExcel(file.getInputStream(), CmsWebsiteFieldImportParam.class, importParams);
            list.forEach(d -> {
                CmsWebsiteField item = JSONUtil.parseObject(JSONUtil.toJSONString(d), CmsWebsiteField.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);
                    }
                    cmsWebsiteFieldService.save(item);
                }
            });
            return success("成功导入" + list.size() + "条", null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fail("导入失败", null);
    }
}
