package com.ruoyi.tc.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.PasswordGenerator;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.tc.entity.Unit;
import com.ruoyi.tc.entity.request.UnitRequest;
import com.ruoyi.tc.regular.AssetCurrentChange;
import com.ruoyi.tc.regular.UnitChange;
import com.ruoyi.tc.service.ExamineInfoService;
import com.ruoyi.tc.service.UnitOtherConcatService;
import com.ruoyi.tc.service.UnitService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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 javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.*;

/**
 * 单位(unit)表控制层
 *
 * @author du
 * @since 2024/11/18 17:11
 */
@Api(tags = "单位表控制层")
@RestController
@PreAuthorize("@ss.hasAnyRoles('admin,common')")
@RequestMapping("/tc/unit")
public class UnitController {

    @Resource
    private UnitService unitService;

    @Resource
    private UnitOtherConcatService unitOtherConcatService;

    @Resource
    private ExamineInfoService examineInfoService;

    @Resource
    private ISysDeptService iSysDeptService;

    @Resource
    private ISysUserService userService;
    @Resource
    private UnitChange unitChange;

    @Resource
    private AssetCurrentChange assetCurrentChange;



    /**
     * 获取单位列表
     */
    @ApiOperation(value = "获取单位列表", response = Unit.class)
    @GetMapping("/list")
    public AjaxResult list(UnitRequest unit) {
        Page<Unit> page = new Page<>();
        page.setSize(unit.getSize());
        page.setCurrent(unit.getCurrent());
        return AjaxResult.success(unitService.page(page, unit));
    }

    /**
     * l1
     */
    @ApiOperation(value = "单位对接")
    @GetMapping("/l1")
    public AjaxResult l1() {
        unitChange.unitTotal();
        return AjaxResult.success();
    }

    /**
     * l2
     */
    @ApiOperation(value = "系统对接")
    @GetMapping("/l2")
    public AjaxResult l2() {
        assetCurrentChange.assetTotal();
        return AjaxResult.success();
    }


    /**
     * 获取所有单位列表
     */
    @ApiOperation(value = "获取所有单位列表", response = Unit.class)
    @GetMapping("/allList")
    public AjaxResult allList(UnitRequest unit) {
        return AjaxResult.success(unitService.selectUnitList(unit));
    }

    /**
     * 单位导出
     */
    @ApiOperation(value = "单位导出")
    @Log(title = "单位导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, UnitRequest unit) {
        List<Unit> list = unitService.selectUnitList(unit);
        ExcelUtil<Unit> util = new ExcelUtil<>(Unit.class);
        util.exportExcel(response, list, "单位数据");
    }

    /**
     * 单位导入
     */
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation(value = "单位导入")
    @Log(title = "单位导入", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) throws Exception {
        ExcelUtil<Unit> util = new ExcelUtil<>(Unit.class);
        List<Unit> list = util.importExcel(file.getInputStream());
        //做组织架构的处理和更新处理
        List<SysDept> sd = iSysDeptService.selectDeptList(new SysDept());
        Set<String> set = new HashSet<>();
        for (SysDept i : sd) {
            set.add(i.getDeptName());
        }
        List<Unit> list1 = unitService.list();
        for (int i = 0; i < list.size(); i++) {
            for (Unit unit : list1) {
                if (unit.getNickName().equals(list.get(i).getNickName())
                        && unit.getUserName().equals(list.get(i).getUserName())
                ) {
                    list.get(i).setId(unit.getId());
                }
            }
            if (set.contains(list.get(i).getDeptName())) {
                for (SysDept s : sd) {
                    if (list.get(i).getDeptName().equals(s.getDeptName())) {
                        list.get(i).setDeptId(s.getDeptId());
                    }
                }
            } else {
                throw new ServiceException("第" + i + "行,组织机构名称填写错误!");
            }
        }
        //批量新增或者修改单位
        unitService.saveOrUpdateBatch(list);
        Map<String, String> a1 = new HashMap<>();
        for (Unit x : list) {
            //查询用户表是否存在该用户
            String s = unitService.validUser(x);
            a1.put(x.getUserName(), s);
        }
        return AjaxResult.success(a1);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<Unit> util = new ExcelUtil<>(Unit.class);
        util.importTemplateExcel(response, "单位模板");
    }

    /**
     * 根据id获取详细信息
     */
    @ApiOperation(value = "根据用户编号获取详细信息")
    @GetMapping("/{id}")
    public AjaxResult getInfo(@PathVariable(value = "id") Long id) {
//        System.out.println(SecurityUtils.encryptPassword("TcZc@2024"));
        return AjaxResult.success(unitService.getById(id));
    }

    /**
     * 新增单位
     */
    @ApiOperation(value = "新增单位")
    @Log(title = "新增单位", businessType = BusinessType.INSERT)
    @PostMapping
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult add(@Valid @RequestBody Unit unit) {
        if (!unitService.lambdaQuery().eq(Unit::getUserName, unit.getUserName()).eq(Unit::getDelFlag, "0").list().isEmpty()) {
            throw new ServiceException(unit.getUserName() + "'已存在单位!");
        }
        //新增单位到单位信息表
        unitService.save(unit);
        //新增其他联系人
        if (unit.getOtherConcat() != null) {
            unit.getOtherConcat().forEach(x -> {
                x.setUnitId(unit.getId());
            });
            unitOtherConcatService.saveBatch(unit.getOtherConcat());
        }
        //新增检查信息
        if (unit.getJcxxList() != null) {
            unit.getJcxxList().forEach(x -> {
                x.setUnitId(unit.getId());
            });
            examineInfoService.saveBatch(unit.getJcxxList());
        }
        String s = unitService.validUser(unit);
        return AjaxResult.success(s);
    }

    /**
     * 修改单位密码
     */
    @ApiOperation(value = "修改单位密码")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @GetMapping("/edit/{id}")
    @PreAuthorize("@ss.hasAnyRoles('admin')")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult editPassword(@PathVariable Long id) {
        String password = PasswordGenerator.password();
        Unit byId = unitService.getById(id);
        SysUser user = userService.selectUserByUserName(byId.getUserName());
        user.setPassword(SecurityUtils.encryptPassword(password));
        userService.updateUserProfile(user);
        return AjaxResult.success(password);
    }

    /**
     * 修改用户
     */
    @ApiOperation(value = "修改用户")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult edit(@Valid @RequestBody Unit x) {
        Unit byId = unitService.getById(x.getId());
        if (!byId.getUserName().equals(x.getUserName()) || !byId.getNickName().equals(x.getNickName())) {
            throw new ServiceException("单位名称和社会信用代码不允许修改!");
        }
        unitService.updateById(x);
        //先删除
        unitOtherConcatService.deleteByUnitIds(x.getId());
        examineInfoService.deleteByUnitIds(x.getId());
        unitService.validUser(x);

        if (x.getOtherConcat() != null) {
            x.getOtherConcat().forEach(y -> {
                y.setUnitId(x.getId());
                y.setConcatId(null);
            });
            unitOtherConcatService.saveBatch(x.getOtherConcat());
        }
        if (x.getJcxxList() != null) {
            x.getJcxxList().forEach(y -> {
                y.setUnitId(x.getId());
                y.setJcid(null);
            });
            examineInfoService.saveBatch(x.getJcxxList());
        }
        return AjaxResult.success();
    }

    /**
     * 删除单位
     */
    @ApiOperation(value = "删除单位")
    @Log(title = "删除单位", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Long id) {
        List<String> userNames = unitService.selectByIds(id);
        //逻辑删除单位和用户
        if (!userNames.isEmpty()) {
            for (String it : userNames) {
                if (it != null) {
                    unitService.deleteUsers(it);
                }
            }
        }
        unitService.deleteUnits(id);
        unitOtherConcatService.deleteByUnitIds(id);
        examineInfoService.deleteByUnitIds(id);
        return AjaxResult.success();
    }

    /**
     * 单位列表过滤
     */
    @ApiOperation(value = "单位列表过滤", response = Unit.class)
    @GetMapping("/dwList")
    public AjaxResult dwList(UnitRequest unit) {
        Page<Unit> page = new Page<>();
        page.setSize(unit.getSize());
        page.setCurrent(unit.getCurrent());
        return AjaxResult.success(unitService.dwList(page, unit));
    }
}
