package org.linlinjava.jz.admin.web;

import io.swagger.models.auth.In;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.subject.Subject;
import org.linlinjava.jz.admin.util.SecurityHelper;
import org.linlinjava.jz.core.util.JacksonUtil;
import org.linlinjava.jz.core.util.MD5Utils;
import org.linlinjava.jz.core.util.ResponseUtil;
import org.linlinjava.jz.core.util.bcrypt.BCryptPasswordEncoder;
import org.linlinjava.jz.core.validator.Order;
import org.linlinjava.jz.core.validator.Sort;
import org.linlinjava.jz.db.domain.JzMallNotice;
import org.linlinjava.jz.db.domain.JzMallNoticeAdmin;
import org.linlinjava.jz.db.domain.JzTicket;
import org.linlinjava.jz.db.domain.SysUser;
import org.linlinjava.jz.db.service.JzMallNoticeAdminService;
import org.linlinjava.jz.db.service.JzMallNoticeService;
import org.linlinjava.jz.db.service.JzSysUserService;
import org.linlinjava.jz.db.service.JzTicketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.linlinjava.jz.admin.util.AdminResponseCode.ADMIN_INVALID_ACCOUNT;

@RestController
@RequestMapping("/admin/profile")
@Validated
public class AdminProfileController {
    private final Log logger = LogFactory.getLog(AdminProfileController.class);

    @Autowired
    private JzSysUserService adminService;
    @Autowired
    private JzMallNoticeService noticeService;
    @Autowired
    private JzMallNoticeAdminService noticeAdminService;
    
    @Autowired
    private JzTicketService jzTicketService;

    @RequiresAuthentication
    @PostMapping("/password")
    public Object create(@RequestBody String body) {
        String oldPassword = JacksonUtil.parseString(body, "oldPassword");
        String newPassword = JacksonUtil.parseString(body, "newPassword");
        if (StringUtils.isEmpty(oldPassword)) {
            return ResponseUtil.badArgument();
        }
        if (StringUtils.isEmpty(newPassword)) {
            return ResponseUtil.badArgument();
        }

        Subject currentUser = SecurityUtils.getSubject();
        SysUser admin = (SysUser) currentUser.getPrincipal();

        /*BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if (!encoder.matches(oldPassword, admin.getUserPassword())) {
            return ResponseUtil.fail(ADMIN_INVALID_ACCOUNT, "账号密码不对");
        }*/
        if (!MD5Utils.stringToMD5(oldPassword).equals(admin.getUserPassword())) {
            return ResponseUtil.fail(ADMIN_INVALID_ACCOUNT, "账号密码不对");
        }

       // String encodedNewPassword = encoder.encode(newPassword);
        admin.setUserPassword(MD5Utils.stringToMD5(oldPassword));

        adminService.updateById(admin);
        return ResponseUtil.ok();
    }


    @RequiresAuthentication
    @GetMapping("/nnotice")
    public Object nNotice() {
        int count = noticeAdminService.countUnread(SecurityHelper.getAdminId());
        return ResponseUtil.ok(count);
    }

    @RequiresAuthentication
    @GetMapping("/lsnotice")
    public Object lsNotice(String title, String type,
                            @RequestParam(defaultValue = "1") Integer page,
                            @RequestParam(defaultValue = "10") Integer limit,
                            @Sort @RequestParam(defaultValue = "add_time") String sort,
                            @Order @RequestParam(defaultValue = "desc") String order) {
        List<JzMallNoticeAdmin> noticeList = noticeAdminService.querySelective(title, type, SecurityHelper.getAdminId(), page, limit, sort, order);
        return ResponseUtil.okList(noticeList);
    }

    @RequiresAuthentication
    @PostMapping("/catnotice")
    public Object catNotice(@RequestBody String body) {
        Integer noticeId = JacksonUtil.parseInteger(body, "noticeId");
        if(noticeId == null){
            return ResponseUtil.badArgument();
        }

        JzMallNoticeAdmin noticeAdmin = noticeAdminService.find(noticeId, SecurityHelper.getAdminId());
        if(noticeAdmin == null){
           return ResponseUtil.badArgumentValue();
        }
        // 更新通知记录中的时间
        noticeAdmin.setReadTime(LocalDateTime.now());
        noticeAdminService.update(noticeAdmin);

        // 返回通知的相关信息
        Map<String, Object> data = new HashMap<>();
        JzMallNotice notice = noticeService.findById(noticeId);
        data.put("title", notice.getTitle());
        data.put("content", notice.getContent());
        data.put("time", notice.getUpdateTime());
        Integer adminId = notice.getAdminId();
        if(adminId.equals(0)){
            data.put("admin", "系统");
        }
        else{
            SysUser admin = adminService.findById(notice.getAdminId());
            data.put("admin", admin.getUserName());
            data.put("avatar", admin.getAvatar());
        }
        return ResponseUtil.ok(data);
    }
    
    @RequiresAuthentication
    @PostMapping("/readNoticeTicketNo")
    public Object readNoticeTicketNo(@RequestBody String body) {
        Integer noticeId = JacksonUtil.parseInteger(body, "noticeId");
        if(noticeId == null){
            return ResponseUtil.badArgument();
        }

        JzMallNoticeAdmin noticeAdmin = noticeAdminService.find(noticeId, SecurityHelper.getAdminId());
        if(noticeAdmin == null){
           return ResponseUtil.badArgumentValue();
        }
        // 更新通知记录中的时间
        noticeAdmin.setReadTime(LocalDateTime.now());
        noticeAdminService.update(noticeAdmin);

        // 返回通知的相关信息
        JzMallNotice notice = noticeService.findById(noticeId);
        String content = notice.getContent(); //String str="工单：Z202101259736<br/>状态：处理中-驳回<br/>操作人：测试";
        
        if(null==content||content.indexOf("<br/>状态")==-1) {
        	return ResponseUtil.ok();
        }
        
        String ticketNo=content.substring(3, content.indexOf("<br/>状态"));
        JzTicket findBySn = jzTicketService.findBySn(ticketNo);
        
       
        return ResponseUtil.ok(findBySn);
    }

    @RequiresAuthentication
    @PostMapping("/bcatnotice")
    public Object bcatNotice(@RequestBody String body) {
        List<Integer> ids = JacksonUtil.parseIntegerList(body, "ids");
        noticeAdminService.markReadByIds(ids, SecurityHelper.getAdminId());
        return ResponseUtil.ok();
    }

    @RequiresAuthentication
    @PostMapping("/rmnotice")
    public Object rmNotice(@RequestBody String body) {
        Integer id = JacksonUtil.parseInteger(body, "id");
        if(id == null){
            return ResponseUtil.badArgument();
        }
        noticeAdminService.deleteById(id, SecurityHelper.getAdminId());
        return ResponseUtil.ok();
    }

    @RequiresAuthentication
    @PostMapping("/brmnotice")
    public Object brmNotice(@RequestBody String body) {
        List<Integer> ids = JacksonUtil.parseIntegerList(body, "ids");
        noticeAdminService.deleteByIds(ids, SecurityHelper.getAdminId());
        return ResponseUtil.ok();
    }
    
    
}
