package yangtz.cs.liu.campus.controller.schooloffical;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.core.utils.HolidayDateUtil;
import com.dingtalk.api.request.OapiMessageCorpconversationAsyncsendV2Request;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileTypeUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.aspectj.apache.bcel.classfile.Module;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import yangtz.cs.liu.campus.domain.file.PubFile;
import yangtz.cs.liu.campus.domain.schooloffical.SchoolOfficial;
import yangtz.cs.liu.campus.domain.schooloffical.SchoolOfficialFlow;
import yangtz.cs.liu.campus.domain.temp.OfficalTemplate;
import yangtz.cs.liu.campus.service.pubFile.IPubFileService;
import yangtz.cs.liu.campus.service.schooloffical.ISchoolOfficalService;
import yangtz.cs.liu.campus.service.schooloffical.ISchoolOfficialFlowService;
import yangtz.cs.liu.campus.service.teacher.ISchoolTeacherService;
import yangtz.cs.liu.campus.util.VxTemlateSendApi;
import yangtz.cs.liu.campus.vo.schoolOfficial.SchoolOfficialFlowVo;
import yangtz.cs.liu.campus.vo.schoolOfficial.SchoolOfficialVo;
import yangtz.cs.liu.campus.vo.schooloffical.SchoolOfficalVO;
import yangtz.cs.liu.dingding.utils.DingMessageUtils;
import yangtz.cs.liu.dingding.vo.DingMessageVo;
import yangtz.cs.liu.wechat.service.api.IWxApiService;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

import static yangtz.cs.liu.campus.constant.OfficalConstant.*;

@RestController
@RequestMapping("/schoolOffical")
public class SchoolOfficalController extends BaseController {
    @Autowired
    private ISchoolOfficalService schoolOfficalService;

    @Autowired
    private ISchoolOfficialFlowService flowService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IPubFileService pubFileService;

    @Autowired
    private IWxApiService wxApiService;

    @Autowired
    private ISchoolTeacherService teacherService;

    @Autowired
    private DingMessageUtils dingMessageUtils;

    @Value("${dd.message-uri}")
    private String messageUrl;

    @Value("${dd.pc-message-uri}")
    private String pcMessageUrl;

    /**
     * 查看
     *
     * @param id
     * @return
     */
    @GetMapping("/getInformation/{id}")
    public AjaxResult getInformation(@PathVariable int id) {
        SchoolOfficial schoolOffical = schoolOfficalService.getById(id);
        return AjaxResult.success(schoolOffical);

    }

    /**
     *点击修改时查询出当前信息
     * @param id
     * @return
     */
    @GetMapping("/getInfo/{id}")
    public AjaxResult getInfo(@PathVariable Long id) {
        SchoolOfficial schoolOffical = schoolOfficalService.getById(id);
        //获取批阅人
        SchoolOfficialFlow flow = flowService.getReviewByOfficialId(id,REVIEWER);
        SysUser user = userService.selectUserById(flow.getReceiveUser());
        SchoolOfficialVo vo = new SchoolOfficialVo();
        BeanUtils.copyProperties(schoolOffical,vo);
        vo.setReceiveUser(flow.getReceiveUser());
        vo.setUserName(user.getUserName());
        return AjaxResult.success(vo);
    }

    /**
       *文件上传之后保存，返回文件信息(PubFile)
     */
    @PostMapping("/importFile")
    public AjaxResult importFile(@RequestParam(value="file",required = false) MultipartFile file) throws IOException {
        //附件信息  //附件地址
        String fileInfo = FileUploadUtils.upload(file);
        //附件名称
        String fileName = fileInfo.substring(fileInfo.lastIndexOf("/") + 1);
        //附件类型
        String fileType = fileInfo.substring(fileInfo.lastIndexOf("."));


        PubFile pubFile=new PubFile();
        pubFile.setFjlx(fileType);
        pubFile.setFjmc(fileName);
        pubFile.setFjdz(fileInfo);
        pubFile.setCreateTime(DateUtils.getNowDate());
        pubFile.setUpdateTime(DateUtils.getNowDate());
        return AjaxResult.success(pubFile);
    }

    /**
     * 暂存
     *分新增时暂存，修改时暂存
     * @param schoolOfficialVo
     * @return
     */
    @PutMapping("/temporary")
    public AjaxResult Temporary(@RequestBody @Validated SchoolOfficialVo schoolOfficialVo) {
        //id为空，新增时暂存
        if(StringUtils.isNull(schoolOfficialVo.getId())){
            //设置发文状态
            schoolOfficialVo.setState(WAIT);
            return toAjax(schoolOfficalService.addStorage(schoolOfficialVo));
        }
        //id不为空，修改时暂存
        return toAjax(schoolOfficalService.storage(schoolOfficialVo));

    }

    /**
     * 发文
     *分新增时发文，修改时发文
     * @param schoolOfficialVo
     * @return
     */
    @PutMapping("/message")
    public AjaxResult Message(@RequestBody @Validated SchoolOfficialVo schoolOfficialVo) {
        schoolOfficialVo.setState(FLOW);
        //新增时发文
        if (StringUtils.isNull(schoolOfficialVo.getId())) {
            int num = schoolOfficalService.addMessage(schoolOfficialVo);
            send(schoolOfficialVo);
            return toAjax(num);
        }
        //修改时发文
        int num = schoolOfficalService.editMessage(schoolOfficialVo);
        send(schoolOfficialVo);
        return toAjax(num);

    }

    /**发送模板消息到批阅人*/
    // TODO 模板消息
    public void send(SchoolOfficialVo vo){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date time = DateUtils.getNowDate();
        String applyTime = format.format(time);

        String applyTime1 = HolidayDateUtil.format1.format(vo.getDeadline());

        //获取钉钉用户id
        String ddUserId = teacherService.getDdUserIdByUserId(vo.getReceiveUser());

        OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
        msg.setOa(new OapiMessageCorpconversationAsyncsendV2Request.OA());
        msg.getOa().setHead(new OapiMessageCorpconversationAsyncsendV2Request.Head());
        msg.getOa().getHead().setText("text");
        msg.getOa().getHead().setBgcolor("FF4BB3F9");
        msg.getOa().setBody(new OapiMessageCorpconversationAsyncsendV2Request.Body());
        msg.getOa().getBody().setAuthor("");
        msg.getOa().getBody().setContent("请您于" + applyTime1 + "前批阅");
        msg.getOa().getBody().setTitle("您好，您有一个新的公文需要批阅");
        msg.getOa().setPcMessageUrl(pcMessageUrl);
        msg.getOa().setMessageUrl(messageUrl);
        msg.setMsgtype("oa");
        DingMessageVo messageVo = new DingMessageVo();
        messageVo.setMsg(msg);
        messageVo.setToAllUser(false);
        messageVo.setUseridList(ddUserId);
        dingMessageUtils.sendMessage(messageVo);

//        //获取openid
//        String openId = teacherService.getOpenIdByUserId(vo.getReceiveUser());
//        Map<String,Object> map = new HashMap<>();
//        map.put("toUserOpenId",openId);
//        map.put("applyTime",applyTime);
//        map.put("remark","请您于" + applyTime1 + "前前往电脑端进行处理。");
//        map.put("applyUser","");
//        map.put("content",vo.getIssuedName());
//        map.put("first","您好，您有一个新的公文需要批阅");
//        VxTemlateSendApi.sendVxTemlate(map);

//        OfficalTemplate template = new OfficalTemplate();
//        template.setFirst("您好，您有一个新的公文需要批阅");
//        //String openId = userService.getOpenIdByUserId(vo.getReceiveUser());
//
//        template.setToUserOpenId(openId);
//        template.setTitle(vo.getIssuedName());
//        template.setFinishTime(vo.getDeadline());
//        template.setContent("请领导批阅");
//        template.setRemark("请您前往电脑端进行处理");
//        String s = wxApiService.sendOfficalTemplate(template);
    }

    /**
     * 发文，列表页操作的发文
     * */
    @PutMapping("/pub/{id}")
    public AjaxResult pub(@PathVariable Long id) {
        int num = schoolOfficalService.pub(id);
        //获取公文详情
        SchoolOfficial schoolOffical = schoolOfficalService.getById(id);
        //获取批阅人
        SchoolOfficialFlow flow = flowService.getReviewByOfficialId(id,REVIEWER);
        SchoolOfficialVo vo = new SchoolOfficialVo();
        BeanUtils.copyProperties(schoolOffical,vo);
        vo.setReceiveUser(flow.getReceiveUser());
        send(vo);
        return toAjax(num);
    }

    /**
     * 删除
     * 级联删除
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public AjaxResult delete(@PathVariable Long id) {
        //先删除子表
        LambdaQueryWrapper<SchoolOfficialFlow> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SchoolOfficialFlow::getOfficialId,id);
        flowService.remove(lqw);
        //删主表
        return toAjax(schoolOfficalService.removeById(id));
    }

    /**
     * 发文搜索
     * 校园管理》公文流转列表
     * @param schoolOffical
     * @return
     */
    @GetMapping("/selectList")
    public TableDataInfo selectList(SchoolOfficial schoolOffical) {
        startPage();
        List<SchoolOfficial> list = schoolOfficalService.selectList(schoolOffical);
        return getDataTable(list);
    }
    /**
     * 发文,带文件
     * 校园管理》公文流转列表
     * @param schoolOffical
     * @return
     */
    @GetMapping("/selectListVo")
    public TableDataInfo selectListVo(SchoolOfficial schoolOffical) {
        startPage();
        List<SchoolOfficialVo> list = schoolOfficalService.selectListVo(schoolOffical);
        return getDataTable(list);
    }
    /**
     * 下载【附件】
     * @param id
     * @param response
     * @throws UnsupportedEncodingException
     */
    @PostMapping("/downloadFile")
    @ResponseBody
    public void download(@RequestParam("id") Long id, HttpServletResponse response) throws IOException {
        PubFile pubFile = pubFileService.getById(id);
        String fjmc = pubFile.getFjmc();

        //文件绝对路径
        String filePath = pubFile.getFjdz();
        String uploadPath = RuoYiConfig.getUploadPath();
        String downPath = (uploadPath+filePath).replaceFirst("/upload/profile/","");
        //String localPath = RuoYiConfig.getDownloadPath();
        // 下载名称
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        FileUtils.setAttachmentResponseHeader(response, downPath);
        FileUtils.writeBytes(downPath, response.getOutputStream());

    }
}
