package yangtz.cs.liu.wechat.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.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.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.wechat.service.api.IWxApiService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isNull;
import static yangtz.cs.liu.campus.constant.ProcessState.PASS;
import static yangtz.cs.liu.campus.constant.ProcessState.REFUSE;

@RestController
@RequestMapping("/wx/purchase")
public class WxSchoolPurchaseController extends BaseController {

    @Autowired
    private ISchoolPurchaseService schoolPurchaseService;
    @Autowired
    private ISchoolPurchaseDetailService schoolPurchaseDetailService;

    @Autowired
    private IProcessService processService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private ISchoolAssetsTypeService typeService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IWxApiService wxApiService;

    @Autowired
    private ISchoolTeacherService teacherService;

    /**
     * 采购审批详情
     */
    @GetMapping("/queryInfo/{id}")
    public AjaxResult queryInfo(@PathVariable Long id) {
        PurchaseVo vo = new PurchaseVo();
        SchoolPurchase purchase = schoolPurchaseService.getById(id);
        BeanUtils.copyProperties(purchase,vo);
        String title = purchase.getPurchaseName() + "-" + purchase.getDeptName() + "-" + purchase.getApplyUser();
        vo.setPurchaseName(title);
        //子表
        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);
    }

    /**
     * 采购审批全部信息
     */
    @GetMapping("/queryInfoAll")
    public AjaxResult queryInfoAll() {
        ArrayList<PurchaseVo> purchaseVos = new ArrayList<>();
        //TODO 根据权限判断是否能够查询

        List<SchoolPurchase> schoolPurchaseList = schoolPurchaseService.list();
        for (SchoolPurchase schoolPurchase : schoolPurchaseList) {
            PurchaseVo purchaseVo = new PurchaseVo();
            BeanUtils.copyProperties(schoolPurchase,purchaseVo);
            String title = schoolPurchase.getPurchaseName() + "-" + schoolPurchase.getDeptName() + "-" + schoolPurchase.getApplyUser();
            purchaseVo.setPurchaseName(title);

            //子表
            LambdaQueryWrapper<SchoolPurchaseDetails> lqw = new LambdaQueryWrapper<>();
            lqw.eq(SchoolPurchaseDetails::getPurchaseId,schoolPurchase.getId());
            List<SchoolPurchaseDetails> list = schoolPurchaseDetailService.list(lqw);
            if(isNull(list) || list.size() == 0){
                purchaseVo.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);
                }
                purchaseVo.setList(voList);
            }

            purchaseVos.add(purchaseVo);
        }
        return AjaxResult.success(purchaseVos);
    }

    /**
     * 采购审批完成任务
     */
    @PostMapping("/complete/{taskId}/{instanceId}/{userId}")
    public AjaxResult complete(@PathVariable("taskId") String taskId,
                               @PathVariable("instanceId") String instanceId,
                               @PathVariable("userId") String userId,
                               @RequestBody Map<String, Object> variables) {
        processService.completeWxTask(taskId, instanceId,userId, variables);
        LambdaQueryWrapper<SchoolPurchase> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SchoolPurchase::getInstanceId, instanceId);
        SchoolPurchase schoolPurchase = schoolPurchaseService.getOne(lqw);
        Boolean flag = (boolean) variables.get("pass");
        /**判断流程是否结束,如果结束则更新状态*/
        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());
            }
            return AjaxResult.success(wxApiService.sendLeaveResultTemplate(template));
        }
        /**发送模板消息到财务领导*/
        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("请您尽快处理。");
        return AjaxResult.success(wxApiService.sendPurchaseTemplate(template));
    }

}
