package com.bcxin.ars.rest.manage;

import cn.hutool.core.bean.BeanUtil;
import com.bcxin.ars.model.Config;
import com.bcxin.ars.model.PageResult;
import com.bcxin.ars.model.sys.Approval;
import com.bcxin.ars.rest.util.manage.ManageResultUtil;
import com.bcxin.ars.rest.util.manage.TableResult;
import com.bcxin.ars.service.sb.ActivityRepairService;
import com.bcxin.ars.service.util.ConfigUtils;
import com.bcxin.ars.service.util.thread.ReSetOldProcessRunnable;
import com.bcxin.ars.util.CTLUtil;
import com.bcxin.ars.util.Constants;
import com.bcxin.ars.util.approval.ApprovalState;
import com.bcxin.ars.util.approval.BusinessType;
import com.bcxin.ars.util.thread.ThreadPoolManager;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * 审批流程管理
 * @author linqinglin
 * @date 2019/01/11 0011 14:56
 */
@Controller
@RequestMapping("manage/approval")
public class ManageApprovalController {

    Logger logger = LoggerFactory.getLogger(ManageApprovalController.class);

    @Autowired
    private ConfigUtils configUtils;

    @Autowired
    private ActivityRepairService activityRepairService;

    /**
     * 审批流程修复页面
     * @return
     */
    @RequestMapping("init")
    public ModelAndView approvalInit() {
        ModelAndView view = new ModelAndView("/manage/approval/manageList");
        return view;
    }


    /**
     * 列表分页查询
     * @param params
     * @param req
     * @return
     */
    @RequestMapping("searchList")
    @ResponseBody
    public TableResult searchList(@RequestParam Map<Object, Object> params, HttpServletRequest req) {
        //查询初始化
        Map<Object, Object> p = CTLUtil.init(req, params);
        Config nativeConfig = configUtils.getConfigByKey(Constants.CURRENT_NATIVE);
        p.put("areaCode", nativeConfig.getValue());
        PageResult page = activityRepairService.searchApprovalList(p);
        TableResult result = new TableResult();
        result.setTotal(page.getTotal());
        result.setRows(page.getRows());
        return result;
    }

    /**
     * 跳到下一步
     * @param approvalId
     * @return
     */
    @RequestMapping("jumpNextProcess/{approvalId}")
    @ResponseBody
    public JSONObject jumpNextProcess(@PathVariable Long approvalId) {
        try {
            activityRepairService.jumpNextProcess(approvalId);
            return ManageResultUtil.returnSuccessJson("操作成功","approvalList","refreshCurrent", "approval/init");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ManageResultUtil.returnFailedJson("操作失败","approvalList", "closeCurrent", "");
        }
    }

    /**
     * 重启流程
     * @param approvalId
     * @return
     */
    @RequestMapping("reStartProcess/{approvalId}")
    @ResponseBody
    public JSONObject approvalReStartProcess(@PathVariable Long approvalId) {
        try {
            activityRepairService.reStartProcess(approvalId);
            return ManageResultUtil.returnSuccessJson("操作成功","approvalList","refreshCurrent", "approval/init");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ManageResultUtil.returnFailedJson("操作失败","approvalList", "closeCurrent", "");
        }
    }

    /**
     * 审批流程打回
     *
     * @param approvalId
     * @return
     */
    @RequestMapping("repulseProcess/{approvalId}")
    @ResponseBody
    public JSONObject approvalRepulseProcess(@PathVariable  Long approvalId) {
        try {
            activityRepairService.repulseProcess(approvalId);
            return ManageResultUtil.returnSuccessJson("操作成功","approvalList","refreshCurrent", "approval/init");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ManageResultUtil.returnFailedJson("操作失败","approvalList", "closeCurrent", "");
        }
    }

    /**
     * 陕西旧审批转新审批
     *
     * @param params
     * @return
     */
    @RequestMapping("resetOldProcess")
    @ResponseBody
    public JSONObject resetOldProcess(@RequestParam Map<Object, Object> params) {
        Config config = configUtils.getConfigByKey("approvalflag");
        if (config != null && config.getValue().equals("1")) {
            config.setValue("0");
            configUtils.updateForKey(config);
            try {
                params.put("oldRev", true);
                params.put("businesstype","004");
                //params.put("areaCode","610832");
                params.put("approvalid","10267");
                PageResult pageResult = activityRepairService.searchApprovalList(params);
                if (pageResult.getRows() != null) {
                    List<Map<Object, Object>> rows = (List<Map<Object, Object>>) pageResult.getRows();
                    ThreadPoolManager threadPoolManager = ThreadPoolManager.newInstance();
                    for (Map<Object, Object> bean : rows) {
                        Approval approval = BeanUtil.mapToBean(bean, Approval.class, true);
                        if (approval != null && !BusinessType.BAYZ.equals(approval.getBusinesstype()) && approval.getOrgid() != null && (ApprovalState.SPZ.equals(approval.getApprovalstate()) || ApprovalState.DSH.equals(approval.getApprovalstate()))) {
                            try {
                                threadPoolManager.addExecuteTask(new ReSetOldProcessRunnable(activityRepairService, approval.getId()));
                            } catch (Exception e) {
                                logger.error(e.getMessage(), e);
                            }
                        }
                    }
                }
                return ManageResultUtil.returnSuccessJson("操作成功","approvalList","closeCurrent", "approval/init");
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
                return ManageResultUtil.returnFailedJson("操作失败","approvalList", "closeCurrent", "");

            }
        } else {
            return ManageResultUtil.returnFailedJson("请勿重复启用！","approvalList", "closeCurrent", "");

        }
    }
}
