package com.repair.controller;

import com.repair.api.RepairAdminControllerAPI;
import com.repair.common.utils.*;
import com.repair.model.enumModel.eIsSuper;
import com.repair.model.enumModel.eStatu;
import com.repair.model.pojo.RepairAdmin;
import com.repair.model.request.freezeRepairAdminRequest;
import com.repair.model.request.updateRepairAdminRequest;
import com.repair.model.result.CommonResult;
import com.repair.model.result.PageUtils;
import com.repair.services.RepairAdminService;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author ceshi
 * @since 2023-07-05
 */
@RestController
public class RepairAdminController implements RepairAdminControllerAPI {

    @Autowired
    private RepairAdminService repairAdminService;

    /**
     * 重置密码
     * @param id
     * @return
     */
    @Override
    public CommonResult resetPassword(String id) {
        RepairAdmin ra = new RepairAdmin();
        ra.setId(id);
        ra.setPassword(AesUtils.encrypt("123456"));
        int updateResult = repairAdminService.updateRepairAdmin(ra);
        if(updateResult <= 0){
            return CommonResult.fail("重置密码失败");
        }
        return CommonResult.ok("重置密码成功");
    }

    /**
     * 添加账号数据
     * 只有超级管理员能添加账号
     * @param ra account 账号
     *           password 密码
     *           username 用户名称
     *           phone 手机号
     * @return
     */
    @Override
    public CommonResult InsertRepairAdmin(@RequestBody RepairAdmin ra, @RequestHeader("user_head") String userhead, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            String st = paramUtils.getParamError(bindingResult);
            return CommonResult.fail(st);
        }

        String userID = AesUtils.decrypt(userhead);
        RepairAdmin operateData = repairAdminService.getRepairById(userID);
        if (!operateData.getIsSuper().equals(eIsSuper.Super.getValue())) {
            return CommonResult.fail("只有超级管理员才能添加账号！");
        }

        // //根据微校卡号判断移动端是否存在数据
        // RepairUser user = repairUserService.getRepairByCardNumber(ra.getCardNumber());
        // if(user == null){
        //     return CommonResult.fail("此账号无法与移动端用户信息进行绑定，新增账号失败");
        // }

        RepairAdmin data = repairAdminService.getRepairByAccount(ra.getAccount());
        if (data != null) {
            return CommonResult.fail("该账号已存在！");
        }

        RepairAdmin cardNumber = repairAdminService.getRepairByCardnumber(ra.getCardNumber());
        if(cardNumber != null){
            if(cardNumber.getIsMobile() == 1){
                ra.setId(cardNumber.getId());
                ra.setIsMobile(0);
                ra.setPassword(AesUtils.encrypt(ra.getPassword()));//加密密码
                int updateResult = repairAdminService.updateRepairAdmin(ra);
                if(updateResult > 0){
                    return CommonResult.ok("添加成功");
                }
            }else{
                return CommonResult.fail("该微校卡号已绑定其他账号！");
            }
        }

        ra.setIsMobile(0);
        int result = repairAdminService.insertRepairAdmin(ra); // 帮我们自动生成id

        return result > 0 ? CommonResult.ok("添加成功") : CommonResult.fail("添加失败");
    }

    /**
     * 查询账户列表数据
     *
     * @param currentPage 当前页
     * @param pageCount   一页数据条数
     * @param account     账号
     * @param startTime   开始时间
     * @param endTime     结束时间
     * @return
     */
    @Override
    public CommonResult queryPageRepairAdmins(@RequestParam int currentPage, @RequestParam int pageCount, String account, String startTime, String endTime) {
        if (startTime != null && endTime != null) {
            try {
                startTime = TimeExchange.getStartOfDayStr(TimeExchange.StringToDate(startTime, "yyyy-MM-dd"));
                endTime = TimeExchange.getEndOfDayStr(TimeExchange.StringToDate(endTime, "yyyy-MM-dd"));
            } catch (Exception e) {
            }
        }

        PageUtils<RepairAdmin> result = repairAdminService.queryPageList(currentPage, pageCount, account, startTime, endTime);

        return CommonResult.ok(result);
    }

    /**
     * 根据ID冻结账号账号数据
     *
     * @param frar id 数据ID
     *             statu 状态
     *             正常：0；冻结：1
     * @return
     */
    @Override
    public CommonResult freezeRepairAdminById(@RequestBody freezeRepairAdminRequest frar, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            String st = paramUtils.getParamError(bindingResult);
            return CommonResult.fail(st);
        }
        RepairAdmin data = repairAdminService.getRepairById(frar.getId());
        if (data == null) {
            return CommonResult.fail("当前数据不存在，解冻失败！");
        }
        if (data.getStatu().equals(frar.getStatu())) {
            String Message = frar.getStatu().equals(eStatu.Freeze.getValue()) ? "当前处于冻结状态，请勿重复操作！" : "当前处于未冻结状态，请勿重复操作！";
            return CommonResult.fail(Message);
        }

        String success = frar.getStatu().equals(eStatu.Freeze.getValue()) ? "冻结成功！" : "解冻成功";
        String fail = frar.getStatu().equals(eStatu.Freeze.getValue()) ? "冻结失败！" : "解冻失败";
        RepairAdmin ra = new RepairAdmin();
        ra.setId(frar.getId());
        ra.setStatu(frar.getStatu());
        int result = repairAdminService.updateRepairAdmin(ra);
        System.out.println(result);
        return result > 0 ? CommonResult.ok(success) : CommonResult.fail(fail);
    }

    /**
     * 根据ID删除账号数据
     *
     * @param id id 数据ID
     * @return
     */
    @Override
    public CommonResult deleteRepairAdminById(@RequestParam String id) {
        RepairAdmin data = repairAdminService.getRepairById(id);
        if (data == null) {
            return CommonResult.fail("当前数据不存在，删除失败！");
        }

        int result = repairAdminService.deleteRepairAdminById(id);

        return result > 0 ? CommonResult.ok() : CommonResult.fail();
    }

    /**
     * 编辑账号
     *
     * @param ra id 数据ID
     *           username 账号名称
     *           phone 手机号
     *           password 密码
     * @return
     */
    @Override
    public CommonResult updateRepairAdminById(updateRepairAdminRequest ra, @RequestHeader("user_head") String userhead, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            String st = paramUtils.getParamError(bindingResult);
            return CommonResult.fail(st);
        }

        RepairAdmin data = repairAdminService.getRepairById(ra.getId());
        if (data == null) {
            return CommonResult.fail("当前数据不存在，编辑失败！");
        }

        //只有操作管理员才能编辑他人的密码
        String userID = AesUtils.decrypt(userhead);
        if (ra.getPassword() != null && !userID.equals(ra.getId())) {
            RepairAdmin operateData = repairAdminService.getRepairById(userID);
            if (operateData == null) {
                return CommonResult.fail("操作身份不合法，编辑失败！");
            }
            if (!data.getPassword().equals(AesUtils.encrypt(ra.getPassword())) && !operateData.getIsSuper().equals(eIsSuper.Super.getValue())) {
                return CommonResult.fail("只有超级管理员才能更改密码！");
            }
        }

        int result = repairAdminService.updateRepaiRadmin(ra);
        return result > 0 ? CommonResult.ok("编辑成功") : CommonResult.fail("编辑失败");
    }

    /**
     * 账号管理导出表单数据
     * @param account 账号
     * @param startTime 起始时间
     * @param endTime 结束时间
     * @param response 响应流
     * @throws NoSuchMethodException
     * @throws InstantiationException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     */
    @Override
    public void downloadRepairAdminExcel(String account, String startTime, String endTime, HttpServletResponse response) throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {

        Map<String, String> map = new HashMap<>();
        //表头与键值对的映射关系
        map.put("username", "昵称");
        map.put("account", "账号");
        map.put("phone", "手机号");
        map.put("updateTimeStr", "创建时间");

        if (startTime != null && endTime != null) {
            try {
                startTime = TimeExchange.getStartOfDayStr(TimeExchange.StringToDate(startTime, "yyyy-MM-dd"));
                endTime = TimeExchange.getEndOfDayStr(TimeExchange.StringToDate(endTime, "yyyy-MM-dd"));
            } catch (Exception e) {
            }
        }

        List<RepairAdmin> datas = repairAdminService.queryRepairAdminList(account, startTime, endTime);

        List<String> orderList = new ArrayList<>();
        orderList.add("username");
        orderList.add("account");
        orderList.add("phone");
        orderList.add("updateTimeStr");

        //导出逻辑 这里的list是从导入里面哪来的 map1与map不一样 orderList这里为空
        Workbook workbook = ExcelExportUtil.createWorkbook(datas, map, 1, "账号管理表", orderList);

        ExcelUtils.excelDownload(workbook, "账号管理.xlsx", response);
    }
}

