package com.zd.airbottle.controller;

import com.zd.airbottle.domain.QpFlowDetail;
import com.zd.airbottle.domain.QpQualificationApply;
import com.zd.airbottle.domain.QpQualificationApplyRecord;
import com.zd.airbottle.domain.vo.QpAirGoodsConfigRelationVo;
import com.zd.airbottle.domain.vo.QpFlowDetailVO;
import com.zd.airbottle.domain.vo.QpQualificationApplyExcelVo;
import com.zd.airbottle.domain.vo.QpQualificationApplyVO;
import com.zd.airbottle.service.*;
import com.zd.common.core.domain.per.PerFun;
import com.zd.common.core.domain.per.PerPrefix;
import com.zd.common.core.utils.poi.ExcelUtil;
import com.zd.common.core.web.controller.BaseController;
import com.zd.common.core.web.domain.AjaxResult;
import com.zd.common.core.web.domain.ResultData;
import com.zd.common.core.web.page.TableDataInfo;
import com.zd.common.log.annotation.Log;
import com.zd.common.log.enums.BusinessType;
import com.zd.common.security.annotation.PreAuthorize;
import com.zd.common.security.service.TokenService;
import com.zd.system.api.domain.SysUser;
import com.zd.system.api.message.RemoteMessageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

/**
 * 用气资格申请Controller
 *
 * @author zd
 * @date 2022-05-10
 */
@RestController
@Api(tags = "【用气资格管理-管理端】")
@RequestMapping("/qualificationApplyManage")
public class QpQualificationApplyManageController extends BaseController
{
    @Autowired
    private IQpQualificationApplyService qpQualificationApplyService;

    @Autowired
    private IQpQualificationApplyDetailService qpQualificationApplyDetailService;

    @Autowired
    private IQpAirBottleService qpAirBottleService;

    @Autowired
    private IQpQualificationApplyRecordService qpQualificationApplyRecordService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private IQpAirGoodsConfigService qpAirGoodsConfigService;

    @Autowired
    private IQpFlowDetailService qpFlowDetailService;

    @Autowired
    private RemoteMessageService remoteMessageService;

    /**
     * 用气资格管理列表
     */
    //@PreAuthorize(hasPermi = "airbottle:apply:list")
    @PreAuthorize(hasPermi = PerPrefix.AIRBOTTLE_QUALIFICATIONAPPLYMANAGE+ PerFun.LIST)
    @GetMapping("/list")
    @ApiOperation(value = "用气资格申请列表",notes = "权限字符："+ PerPrefix.AIRBOTTLE_QUALIFICATIONAPPLYMANAGE+ PerFun.LIST)
    public TableDataInfo<QpQualificationApplyVO> list(QpQualificationApplyVO qpQualificationApply)
    {
        //获取当前登录用户信息
        SysUser sysUser = tokenService.getLoginUser().getSysUser();
        qpQualificationApply.setUserId(sysUser.getUserId());

        startPage();
        List<QpQualificationApplyVO> list = qpQualificationApplyService.selectQpQualificationApplyList(qpQualificationApply);
        return getDataTable(list);
    }

    /**
     * 用气资格管理列表
     */
    @PreAuthorize(hasPermi = PerPrefix.AIRBOTTLE_QUALIFICATIONMANAGE+ PerFun.LIST)
    @GetMapping("/listManage")
    @ApiOperation(value = "用气资格管理列表",notes = "权限字符："+ PerPrefix.AIRBOTTLE_QUALIFICATIONMANAGE+ PerFun.LIST)
    public TableDataInfo<QpQualificationApplyVO> listManage(QpQualificationApplyVO qpQualificationApply)
    {
        qpQualificationApply.setCenterAuditStatus(1);//审核通过的数据
        qpQualificationApply.setRemark("100");
        startPage();
        List<QpQualificationApplyVO> list = qpQualificationApplyService.selectQpQualificationApplyManageList(qpQualificationApply);
        return getDataTable(list);
    }

    /***
     * 资格审核列表
     * @param applyVO
     * @return
     */
    @PreAuthorize(hasPermi = PerPrefix.AIRBOTTLE_QUALIFICATIONAUDITMANAGE+ PerFun.LIST)
    @GetMapping("/auditList")
    @ApiOperation(value = "用气资格管理列表",notes = "权限字符："+PerPrefix.AIRBOTTLE_QUALIFICATIONAUDITMANAGE+ PerFun.LIST )
    public TableDataInfo<QpQualificationApplyVO> auditList(QpQualificationApplyVO applyVO)
    {
        startPage();
        //applyVO.setAuditStatus(0);//未审核完成的数据
        // List<QpQualificationApplyVO> list = qpQualificationApplyService.selectQpApplyList(applyVO);
        List<QpQualificationApplyVO> list = qpQualificationApplyService.selectQpQualificationApplyList(applyVO);
        return getDataTable(list);
    }

    /**
     * 导出资格申请列表
     */
    @ApiOperation(value = "导出资格申请列表",notes = "权限字符："+PerPrefix.AIRBOTTLE_QUALIFICATIONAPPLYMANAGE+ PerFun.EXPORT)
    //@PreAuthorize(hasPermi = "airbottle:apply:export")
    @PreAuthorize(hasPermi = PerPrefix.AIRBOTTLE_QUALIFICATIONAPPLYMANAGE+ PerFun.EXPORT)
    @Log(title = "资格申请", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, QpQualificationApplyVO qpQualificationApply) throws IOException
    {
        //获取当前登录用户信息
        //SysUser sysUser = tokenService.getLoginUser().getSysUser();
        //qpQualificationApply.setApplyUserid(sysUser.getUserId());//当前登陆人申请数据
        qpQualificationApply.setCenterAuditStatus(1);//审核通过的数据
        qpQualificationApply.setRemark("100");
        List<QpQualificationApplyVO> list = qpQualificationApplyService.selectQpQualificationApplyList(qpQualificationApply);
        ExcelUtil<QpQualificationApplyExcelVo> util = new ExcelUtil<>(QpQualificationApplyExcelVo.class);
        List<QpQualificationApplyExcelVo> listExcel = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (QpQualificationApplyVO applyVO:list) {
            QpQualificationApplyExcelVo excelVo = new QpQualificationApplyExcelVo();
            excelVo.setApplyUser(applyVO.getApplyUser());//姓名
            excelVo.setPhone(applyVO.getPhone());//电话
            excelVo.setLocation(applyVO.getLocation());//实验地点
            excelVo.setBottleNumber(applyVO.getBottleNumber());//气瓶数量
            excelVo.setStrTime(sdf.format(applyVO.getStartTime())+" ~ "+ sdf.format(applyVO.getEndTime()));//使用期限
            listExcel.add(excelVo);
        }

        //本地日期,不包括时分秒
        LocalDate nowDate = LocalDate.now();
        util.exportExcel(response, listExcel, "资格信息数据", null, "资格信息数据导出表"+nowDate);
    }

    /**
     * 获取资格申请详细信息
     */
    @ApiOperation(value = "获取资格申请详细信息",notes = "权限字符："+PerPrefix.AIRBOTTLE_QUALIFICATIONAPPLYMANAGE+ PerFun.QUERY)
    //@PreAuthorize(hasPermi = "airbottle:apply:query")
    @PreAuthorize(hasPermi = PerPrefix.AIRBOTTLE_QUALIFICATIONAPPLYMANAGE+ PerFun.QUERY)
    @GetMapping(value = "/{id}")
    public ResultData<QpQualificationApply> getInfo(@PathVariable("id") Long id)
    {
        return ResultData.success(qpQualificationApplyService.selectQpQualificationApplyById(id));
    }

    /**
     * 获取资格申请详细信息
     */
    @ApiOperation(value = "获取资格申请详细信息",notes = "权限字符："+PerPrefix.AIRBOTTLE_QUALIFICATIONAPPLYMANAGE+ PerFun.QUERY)
    //@PreAuthorize(hasPermi = "airbottle:apply:query")
    @PreAuthorize(hasPermi = PerPrefix.AIRBOTTLE_QUALIFICATIONAPPLYMANAGE+ PerFun.QUERY)
    @GetMapping("/getById")
    public AjaxResult getById( Long id)
    {
        //获取当前登录用户信息
        SysUser sysUser = tokenService.getLoginUser().getSysUser();
        Map<String,Object> map = new HashMap<>();
        //申请单详情
        QpQualificationApplyVO qpQualificationApply =qpQualificationApplyService.selectQpQualificationApplyById(id);
        map.put("apply",qpQualificationApply);

        boolean isAdmin =false;//是否实验室负责人
        boolean audit = false;//是否有审核资格
        //判断当前的登录用户是否该实验室负责人
        if(sysUser.getUserId().equals(qpQualificationApply.getAdminId()) ) {
            isAdmin=true;
            audit=true;
        }

        //待审核或者驳回
       /* if(0 == qpQualificationApply.getLeadAuditStatus() || 2 == qpQualificationApply.getLeadAuditStatus()){
            if(sysUser.getUserId().equals(qpQualificationApply.getAdminId()) ) {
                audit=true;
            }
        } else */
            if(1 == qpQualificationApply.getLeadAuditStatus()){
            //查询登录用户是否有实验中心审核资格
            QpFlowDetail flowDetail = qpFlowDetailService.selectZgCenterByUserIdIs(sysUser.getUserId());
            if(flowDetail!=null){
                audit=true;
            }
        }
        map.put("isAdmin",isAdmin);
        map.put("audit",audit);

        //申请气瓶详情
        /*QpQualificationApplyDetailVO detailVO = new QpQualificationApplyDetailVO();
        detailVO.setQualificateApplyId(qpQualificationApply.getId());
        List<QpQualificationApplyDetailVO> airBottlelist = qpQualificationApplyDetailService.selectQpQualificationApplyDetailListRelation(detailVO);
        */
        List<QpAirGoodsConfigRelationVo> airBottlelist = qpQualificationApplyDetailService.selectQpQualificationApplyDetailListRelation(qpQualificationApply.getId());
        map.put("airBottlelist",airBottlelist);

        //审核记录
        QpQualificationApplyRecord auditlog = new QpQualificationApplyRecord();
        auditlog.setQualificationApplyId(id);
        List<QpQualificationApplyRecord> auditlist= qpQualificationApplyRecordService.selectQpQualificationApplyRecordList(auditlog);
        map.put("auditlist",auditlist);

        return AjaxResult.success(map);
    }

    /**
     * 新增资格申请
     */
    @ApiOperation(value = "新增资格申请",notes = "权限字符："+PerPrefix.AIRBOTTLE_QUALIFICATIONAPPLYMANAGE+ PerFun.ADD)
    //@PreAuthorize(hasPermi = "airbottle:apply:add")
    @Log(title = "资格申请", businessType = BusinessType.INSERT)
    @PreAuthorize(hasPermi = PerPrefix.AIRBOTTLE_QUALIFICATIONAPPLYMANAGE+ PerFun.ADD)
    @PostMapping
    public ResultData<Boolean> add(@RequestBody QpQualificationApplyVO qpQualificationApplyVo)
    {
        return ResultData.result(qpQualificationApplyService.insertQpQualificationApply(qpQualificationApplyVo));
    }

    @ApiOperation(value = "新增资格重新申请")
    @PreAuthorize(hasPermi = "airbottle:apply:add")
    @Log(title = "资格重新申请", businessType = BusinessType.INSERT)
    //@PreAuthorize(hasPermi = PerPrefix.AIRBOTTLE_QUALIFICATIONAPPLY+ PerFun.ADD)
    @PostMapping("/reapply")
    public ResultData<Boolean> reapply(@RequestBody QpQualificationApply qpQualificationApply)
    {
        return ResultData.result(qpQualificationApplyService.updateQpQualificationApplyRepeat(qpQualificationApply));
    }

    /**
     * 修改资格申请
     */
    @ApiOperation(value = "修改资格申请",notes = "权限字符："+PerPrefix.AIRBOTTLE_QUALIFICATIONAPPLYMANAGE+ PerFun.EDIT)
    //@PreAuthorize(hasPermi = "airbottle:apply:edit")
    @PreAuthorize(hasPermi = PerPrefix.AIRBOTTLE_QUALIFICATIONAPPLYMANAGE+ PerFun.EDIT)
    @Log(title = "资格申请", businessType = BusinessType.UPDATE)
    @PutMapping
    public ResultData<Boolean> edit(@RequestBody QpQualificationApply qpQualificationApply)
    {
        return  ResultData.result(qpQualificationApplyService.updateQpQualificationApply(qpQualificationApply));
    }

    /**
     * 实验中心审核
     */
    //@ApiOperation(value = "实验中心审核",notes = "权限字符："+PerPrefix.AIRBOTTLE_QUALIFICATIONAPPLYMANAGE+ "centerexamine")
    //@PreAuthorize(hasPermi = "airbottle:apply:centerexamine")
    //@PreAuthorize(hasPermi = PerPrefix.AIRBOTTLE_QUALIFICATIONAPPLYMANAGE+ "centerexamine")
    @Log(title = "实验中心审核", businessType = BusinessType.UPDATE)
    @PostMapping("/centerExamine")
    public ResultData<Boolean> centerExamine(@RequestBody QpQualificationApply qpQualificationApply)
    {
        //获取当前登录用户信息
        SysUser sysUser = tokenService.getLoginUser().getSysUser();

        //审核表数据录入
        QpQualificationApplyRecord record = new QpQualificationApplyRecord();
        record.setAuditUser(sysUser.getNickName());
        record.setAuditUserid(sysUser.getUserId());
        record.setAuditTime(new Date());
        record.setAuditStatus(qpQualificationApply.getCenterAuditStatus());
        record.setRemark(qpQualificationApply.getCenterAuditCause());
        record.setQualificationApplyId(qpQualificationApply.getId());
        record.setAuditType(2L);
        int flg = qpQualificationApplyRecordService.insertQpQualificationApplyRecord(record);


        qpQualificationApply.setCenterAuditUserid(sysUser.getUserId());
        qpQualificationApply.setCenterAuditUsername(sysUser.getNickName());
        qpQualificationApply.setCenterAuditTime(new Date());

        if(flg>0){
            //消息发送
            QpQualificationApplyVO qualificationApply = qpQualificationApplyService.selectQpQualificationApplyById(qpQualificationApply.getId());
            /*checkType "审核类型 1：资格申请 2：用气申请"),
            checkStatus "审核状态 1：通过 2：已驳回"),
            checkTime "审核时间")*/
            remoteMessageService.check(qualificationApply.getUserId(),1,qpQualificationApply.getCenterAuditStatus(),new Date(),qpQualificationApply.getId());
        }
       return  ResultData.result(qpQualificationApplyService.updateQpQualificationApply(qpQualificationApply));
    }

    /**
     * 实验室负责人审核
     */
    //@ApiOperation(value = "实验室负责人审核",notes = "权限字符："+PerPrefix.AIRBOTTLE_QUALIFICATIONAPPLYMANAGE+ "leadexamine")
    //@PreAuthorize(hasPermi = "airbottle:apply:leadexamine")
    //@PreAuthorize(hasPermi = PerPrefix.AIRBOTTLE_QUALIFICATIONAPPLYMANAGE+ "leadexamine")
    @Log(title = "实验室负责人审核", businessType = BusinessType.UPDATE)
    @PostMapping("/leadExamine")
    public ResultData<Boolean> leadExamine(@RequestBody QpQualificationApply qpQualificationApply)
    {
        //获取当前登录用户信息
        SysUser sysUser = tokenService.getLoginUser().getSysUser();

        //审核表数据录入
        QpQualificationApplyRecord record = new QpQualificationApplyRecord();
        record.setAuditUser(sysUser.getNickName());
        record.setAuditUserid(sysUser.getUserId());
        record.setAuditTime(new Date());
        record.setAuditStatus(qpQualificationApply.getLeadAuditStatus());
        record.setRemark(qpQualificationApply.getLeadAuditCause());
        record.setQualificationApplyId(qpQualificationApply.getId());
        record.setAuditType(1L);
        qpQualificationApplyRecordService.insertQpQualificationApplyRecord(record);


        qpQualificationApply.setLeadAuditUserid(sysUser.getUserId());
        qpQualificationApply.setLeadAuditUsername(sysUser.getNickName());
        qpQualificationApply.setLeadAuditTime(new Date());

        if(2==qpQualificationApply.getLeadAuditStatus()){
            //实验室审核驳回时 消息发送
            QpQualificationApplyVO qualificationApply = qpQualificationApplyService.selectQpQualificationApplyById(qpQualificationApply.getId());
            /*checkType "审核类型 1：资格申请 2：用气申请"),
            checkStatus "审核状态 1：通过 2：已驳回"),
            checkTime "审核时间")*/
            remoteMessageService.check(qualificationApply.getUserId(),1,2,new Date(),qpQualificationApply.getId());
        }


        return  ResultData.result(qpQualificationApplyService.updateQpQualificationApply(qpQualificationApply));
    }

    /**
     * 删除资格申请
     */
    @ApiOperation(value = "删除资格申请",notes = "权限字符："+PerPrefix.AIRBOTTLE_QUALIFICATIONAPPLYMANAGE+ PerFun.REMOVE)
   // @PreAuthorize(hasPermi = "airbottle:apply:remove")
    @PreAuthorize(hasPermi = PerPrefix.AIRBOTTLE_QUALIFICATIONAPPLYMANAGE+ PerFun.REMOVE)
    @Log(title = "资格申请", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public ResultData<Boolean> remove(@PathVariable Long[] ids)
    {
        return ResultData.result(qpQualificationApplyService.deleteQpQualificationApplyByIds(ids));
    }

    /**
     * 获取当前登录用户信息
     */
    @ApiOperation(value = "获取资格申请详细信息")
    @GetMapping("/getLoginUser")
    public ResultData<SysUser> getLoginUser()
    {
        //获取当前登录用户信息
        SysUser sysUser = tokenService.getLoginUser().getSysUser();
        return ResultData.success(sysUser);
    }

    /**
     * 查询资格申请气瓶列表
     */
   /* @PreAuthorize(hasPermi = PerPrefix.AIRBOTTLE_QUALIFICATIONAPPLYMANAGE+ "apply")
    @GetMapping("/listApply")
    @ApiOperation(value = "查询资格申请气瓶列表")
    public TableDataInfo<QpAirBottleVO> listQp(QpAirBottleVO qpAirBottleVO)
    {
        startPage();
        List<QpAirBottleVO> list = qpAirBottleService.selectQpAirBottleListByParameter(qpAirBottleVO);
        return getDataTable(list);
    }*/


    /***
     * 查询所有供应商气瓶信息
     * @param relationVo
     * @return
     */
    @GetMapping("/listAllGoods")
    @ApiOperation(value = "查询资格申请气瓶列表")
    public TableDataInfo<QpAirGoodsConfigRelationVo> listAllGoods(QpAirGoodsConfigRelationVo relationVo)
    {
        startPage();
        List<QpAirGoodsConfigRelationVo> list =  qpAirGoodsConfigService.selectQpAirGoodsConfigRelationList(relationVo);
        return getDataTable(list);
    }

}
