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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
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.system.service.ISysUserService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import yangtz.cs.liu.activiti.domain.HistoricActivity;
import yangtz.cs.liu.activiti.service.IProcessService;
import yangtz.cs.liu.campus.domain.assetsType.SchoolAssetsType;
import yangtz.cs.liu.campus.domain.purchase.SchoolPurchase;
import yangtz.cs.liu.campus.domain.purchase.SchoolPurchaseDetails;
import yangtz.cs.liu.campus.domain.temp.LeaveResultTemplate;
import yangtz.cs.liu.campus.domain.temp.PurchaseTemplate;
import yangtz.cs.liu.campus.service.assetsType.ISchoolAssetsTypeService;
import yangtz.cs.liu.campus.service.purchase.ISchoolPurchaseDetailService;
import yangtz.cs.liu.campus.service.purchase.ISchoolPurchaseService;
import yangtz.cs.liu.campus.service.teacher.ISchoolTeacherService;
import yangtz.cs.liu.campus.vo.purchase.SchoolPurchaseDetailsVo;
import yangtz.cs.liu.campus.vo.purchase.PurchaseVo;
import yangtz.cs.liu.campus.vo.purchase.SchoolPurchaseVo;
import yangtz.cs.liu.wechat.service.api.IWxApiService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isNull;
import static com.core.constant.ProcessDefinition.PURCHASEREQUEST;
import static yangtz.cs.liu.campus.constant.ProcessState.*;

@RestController
@RequestMapping("/purchaseApproval")
public class SchoolPurchaseController extends BaseController {
    @Autowired
    private ISchoolPurchaseService schoolPurchaseService;
    @Autowired
    private ISchoolPurchaseDetailService schoolPurchaseDetailService;

    @Autowired
    private IProcessService processService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private IWxApiService wxApiService;

    @Autowired
    private ISchoolAssetsTypeService typeService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISchoolTeacherService teacherService;

    /**
     * 采购申请——新增
     */
    @PostMapping("/addPurchase")
    public AjaxResult addPurchase(@RequestBody @Validated PurchaseVo purchase) {
        return toAjax(schoolPurchaseService.insertSchoolPurchase(purchase));
    }

    /**
     * 采购申请——删除
     *
     * @param id
     * @return
     */
    @DeleteMapping("/deletePurchase/{id}")
    @Transactional
    public AjaxResult deletePurchase(@PathVariable Long id) {
        //先删子表
        LambdaQueryWrapper<SchoolPurchaseDetails> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SchoolPurchaseDetails::getPurchaseId,id);
        schoolPurchaseDetailService.remove(lqw);
        return toAjax(schoolPurchaseService.removeById(id));
    }

    /**
     * 采购申请——列表submitState 0未提交，1已提交
     * @return
     */
    @GetMapping("/queryListApply")
    public TableDataInfo queryListApply(@RequestParam("submitState") String submitState,SchoolPurchase schoolPurchase){
        if (getDeptId() == null){
            throw new ServiceException("未查询到当前部门id");
        }
        schoolPurchase.setDeptId(getDeptId());
        startPage();
        List<SchoolPurchaseVo> list = schoolPurchaseService.queryList(submitState,schoolPurchase);
        return getDataTable(list);
    }

    /**
     * 采购申请——修改时查询出当前信息
     *
     * @param id
     * @return
     */
    @GetMapping("/listApplyOne/{id}")
    public AjaxResult listApplyOne(@PathVariable("id") Long id) {
        PurchaseVo vo = new PurchaseVo();
        SchoolPurchase purchase = schoolPurchaseService.getById(id);
        BeanUtils.copyProperties(purchase,vo);
        //子表
        LambdaQueryWrapper<SchoolPurchaseDetails> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SchoolPurchaseDetails::getPurchaseId,id);
        List<SchoolPurchaseDetails> list = schoolPurchaseDetailService.list(lqw);
        if(isNull(list) || list.size() == 0){
            vo.setList(new ArrayList<>());
        }else{
            List<SchoolPurchaseDetailsVo> voList = new ArrayList<>();
            for(SchoolPurchaseDetails details : list){
                SchoolPurchaseDetailsVo dv = new SchoolPurchaseDetailsVo();
                BeanUtils.copyProperties(details,dv);
                SchoolAssetsType type = typeService.getById(details.getAssetsType());
                dv.setAssetsTypeName(type.getTypeName());
                voList.add(dv);
            }
            vo.setList(voList);
        }
        return AjaxResult.success(vo);
    }

    /**
     * 采购申请——修改
     *
     * @param purchaseVo
     * @return
     */
    @PutMapping("/editApply")
    public AjaxResult editApply(@RequestBody PurchaseVo purchaseVo) {
        if (StringUtils.isNull(purchaseVo.getId())) {
            throw new ServiceException("id不能为空");
        }
       return toAjax(schoolPurchaseService.editSchoolPurchase(purchaseVo));
    }

    /**
     * 提交申请
     * @param id
     * @return
     */
    @PostMapping("/submitApply/{id}")
    public AjaxResult submitApply(@PathVariable("id") Long id) {
        SchoolPurchase schoolPurchase = schoolPurchaseService.getById(id);
        if (StringUtils.isNull(schoolPurchase)) {
            throw new ServiceException("提交申请失败,未查询到相关信息");
        }
        String userName = getUsername();
        schoolPurchase.setApplyId(getUserId());
        schoolPurchase.setApplyUser(userName);
        schoolPurchase.setApplyTime(DateUtils.getNowDate());
        schoolPurchaseService.submitApply(schoolPurchase, userName, PURCHASEREQUEST, new HashMap<>());

        /**发送模板消息到处室领导*/
        PurchaseTemplate template = new PurchaseTemplate();
        //String openId = userService.getOpenIdByUserId(schoolPurchase.getHandUserId1());
        String openId = teacherService.getOpenIdByUserId(schoolPurchase.getHandUserId1());
        template.setToUserOpenId(openId);
        template.setFirst("您好，您有采购申请等待审批。");
        template.setApplyUser(schoolPurchase.getApplyUser());
        template.setContent(schoolPurchase.getPurchaseName());
        template.setApplyTime(schoolPurchase.getApplyTime());
        template.setRemark("请您尽快处理。");
        wxApiService.sendPurchaseTemplate(template);
        return AjaxResult.success("审批完成");
    }

    /**
     * 待办事项列表
     *
     * @param schoolPurchase
     * @return
     */
    @GetMapping("/taskList")
    public TableDataInfo taskList(SchoolPurchase schoolPurchase) {
        String userId = getUserId().toString();
        List<SchoolPurchaseVo> list = schoolPurchaseService.toDoList(PURCHASEREQUEST, schoolPurchase, userId);
        //int total = processService.getTodoTotal(PURCHASEREQUEST, userId);
        return getTaskTable(list, list.size());
    }

    /**
     * 完成任务
     *
     * @param taskId
     * @param instanceId
     * @param variables
     * @return
     */
    @PostMapping("/complete/{taskId}/{instanceId}")
    public AjaxResult complete(@PathVariable("taskId") String taskId, @PathVariable("instanceId") String instanceId, @RequestBody Map<String, Object> variables) {
        processService.completeTask(taskId, instanceId, variables);
        LambdaQueryWrapper<SchoolPurchase> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SchoolPurchase::getInstanceId, instanceId);
        SchoolPurchase schoolPurchase = schoolPurchaseService.getOne(lqw);
        //Boolean flag = (boolean) variables.get("pass");
        Boolean flag = Boolean.parseBoolean(variables.get("pass").toString());
        /**判断流程是否结束,如果结束则更新教师请假状态*/
        ProcessInstance rpi = runtimeService
                .createProcessInstanceQuery()//创建流程实例查询对象
                .processInstanceId(instanceId)
                .singleResult();
        //说明流程实例结束了
        if (rpi == null) {
            if (flag) {
                schoolPurchase.setState(PASS);
            } else {
                schoolPurchase.setState(REFUSE);
            }
            /** 修改任务结果 */
            schoolPurchaseService.updateById(schoolPurchase);
            /**发送模板消息到申请人，审批结果*/
            LeaveResultTemplate template = new LeaveResultTemplate();
            template.setFirst("您好，您的采购申请已回复。");
            //获取申请人openId
            //String openId = userService.getOpenIdByUserId(schoolPurchase.getApplyId());
            String openId = teacherService.getOpenIdByUserId(schoolPurchase.getApplyId());
            template.setToUserOpenId(openId);
            template.setResult(flag ? "已通过" : "已驳回");
            template.setRemark("审批留言： "+ variables.get("comment"));
            List<HistoricActivity> list = processService.selectHistoryList(instanceId,new HistoricActivity());
            if(StringUtils.isNotNull(list) && list.size() > 0){
                HistoricActivity activity = list.get(0);
                template.setAuditTime(activity.getEndTime());
            }
            wxApiService.sendLeaveResultTemplate(template);
            return AjaxResult.success("审批完成");
        }
        /**发送模板消息到财务领导*/
        PurchaseTemplate template = new PurchaseTemplate();
        //String openId = userService.getOpenIdByUserId(schoolPurchase.getHandUserId2());
        String openId = teacherService.getOpenIdByUserId(schoolPurchase.getHandUserId2());
        template.setToUserOpenId(openId);
        template.setFirst("您好，您有采购申请等待审批。");
        template.setApplyUser(schoolPurchase.getApplyUser());
        template.setContent(schoolPurchase.getPurchaseName());
        template.setApplyTime(schoolPurchase.getApplyTime());
        template.setRemark("请您尽快处理。");
        wxApiService.sendPurchaseTemplate(template);
        return AjaxResult.success("审批完成");
    }

    /**
     * 我的已办列表
     *
     * @param schoolPurchase
     * @return
     */
    @GetMapping("/taskDoneList")
    public TableDataInfo taskDoneList(SchoolPurchase schoolPurchase) {
        String userId = getUserId().toString();
        List<SchoolPurchaseVo> list = schoolPurchaseService.DoneList(PURCHASEREQUEST, schoolPurchase, userId);
        //int total = processService.getDoneTotal(PURCHASEREQUEST, userId);
        return getTaskTable(list, list.size());
    }

    /**
     * 采购信息——新增
     *
     * @param schoolPurchase
     * @return
     */
    @PostMapping("/addRegister")
    public AjaxResult addRegister(@RequestBody SchoolPurchase schoolPurchase) {
        schoolPurchase.setCreateBy(getUsername());
        schoolPurchase.setCreateTime(DateUtils.getNowDate());
        return toAjax(schoolPurchaseService.addPurchase(schoolPurchase));
    }

    /**
     * 采购信息——搜索
     *
     * @param schoolPurchase
     * @return
     */
    @GetMapping("/selectRegister")
    public TableDataInfo selectRegister(@RequestBody SchoolPurchase schoolPurchase) {
        startPage();
        List<SchoolPurchase> list = schoolPurchaseService.selectListRegister(schoolPurchase);
        if (list.size() <= 0) {
            throw new ServiceException("查询失败或没有数据");
        }
        return getDataTable(list);
    }

    /**
     * 采购信息——详情
     *
     * @param id
     * @return
     */
    @GetMapping("/selectRegisterById/{id}")
    public AjaxResult selectRegisterById(@PathVariable("id") Long id) {
        return AjaxResult.success(schoolPurchaseService.getById(id));
    }

    /**
     * 采购信息——加载页面
     * @return
     */
    @GetMapping("/selectRegisterList")
    public TableDataInfo selectRegisterList(SchoolPurchase schoolPurchase){
        startPage();
        List<SchoolPurchase> list = schoolPurchaseService.selectListRegister(schoolPurchase);
        return getDataTable(list);
    }

    /**
     * 资金使用明细列表
     * @param schoolPurchase
     * @return
     */
    @GetMapping("/selectPurchaseList")
    public TableDataInfo selectPurchaseList(SchoolPurchase schoolPurchase){
        startPage();
        List<SchoolPurchaseVo> list = schoolPurchaseService.selectPurchaseList(schoolPurchase);
        return getDataTable(list);
    }

}
