package com.engine.htxc.contract.web;

import com.alibaba.fastjson.JSON;
import com.engine.htsc.workflow.util.WorkflowUtil;
import com.engine.htxc.common.R;
import com.engine.htxc.contract.util.ContractUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author      : wanxq
 * @Date        : 2022年05月27日09:43:26
 * @Version     : 1.0
 * @Description : 合同审批流程相关接口
 **/
public class ContractApprovalAction {

    private static final Logger LOG = LoggerFactory.getLogger(ContractApprovalAction.class);

    /**
     * @description: 更新合同状态
     * @version: 1.0
     * @author: wanxq
     * @date: 2022年07月12 17:08:44
     * @param: [request, response]
     * @return: java.lang.String
     **/
    @POST
    @Path("/contractstatus/update")
    @Produces({MediaType.TEXT_PLAIN})
    public String updateContractStatus(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        String contractids = Util.null2String(request.getParameter("contractids"));
        String zt = Util.null2String(request.getParameter("zt"));

        try {
            String updateSql = "  update uf_htqc set zt="+zt+" where id in("+contractids+") ";
            RecordSet rs = new RecordSet();
            boolean result = rs.execute(updateSql);
            if(result){
                return JSON.toJSONString(R.ok());
            }else {
                return JSON.toJSONString(R.error("合同状态更新失败"));
            }
        } catch (Exception e) {
            LOG.error("更新合同状态出错：",e);
            return JSON.toJSONString(R.error());
        }
    }

    /**
     * @description: 更新合同附件
     * @version: 1.0
     * @author: wanxq
     * @date: 2022年07月26 13:24:12
     * @param: [request, response]
     * @return: java.lang.String
     **/
    @POST
    @Path("/updateWfContractFile")
    @Produces({MediaType.TEXT_PLAIN})
    public String updateWfContractFile(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        String fileids = Util.null2String(request.getParameter("fileids"));
        String requestid = Util.null2String(request.getParameter("requestid"));

        try {
            RecordSet rs = new RecordSet();
            String tableName = WorkflowUtil.getTableName(requestid);
            String updateSql = " update "+tableName+" set htfj=? where requestid=? ";
            boolean result = rs.executeUpdate(updateSql,new Object[]{fileids,requestid});
            if(result){
                return JSON.toJSONString(R.ok());
            }else {
                return JSON.toJSONString(R.error("更新合同附件失败"));
            }

        } catch (Exception e) {
            LOG.error("更新合同附件出错：",e);
            return JSON.toJSONString(R.error());
        }
    }

    /**
     * @description:查询合同编辑地址
     * @version: 1.0
     * @author: wanxq
     * @date: 2022年07月27 13:51:33
     * @param: [request, response]
     * @return: java.lang.String
     **/
    @GET
    @Path("/contract/getEditUrl")
    @Produces({MediaType.TEXT_PLAIN})
    public String getEditUrl(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        Map<String, Object> apidatas = new HashMap<>();
        int requestid = Util.getIntValue(request.getParameter("requestid"));
        int nodeid = Util.getIntValue(request.getParameter("nodeid"));
        int wfuserid = Util.getIntValue(request.getParameter("f_weaver_belongto_userid"));
        String wfunnumber = Util.null2String(request.getParameter("wfunnumber"));
        String nodeunnumber = Util.null2String(request.getParameter("nodeunnumber"));
        String htlx = Util.null2String(request.getParameter("htlx"));

        RecordSet rs = new RecordSet();
        Map<String,Object> data = new HashMap<>();
        data.put("hasRight", false);
        data.put("isEdit", false);

        //判断是否是流程当前节点参与人
        String url = "";
        String sql = " select 1 from workflow_currentoperator where requestid=? and nodeid=? and userid=? ";

        try {
            rs.executeQuery(sql,new Object[]{requestid,nodeid,wfuserid});
            if(rs.next() || requestid<0){
                url = ContractUtil.getEditUrl(wfunnumber,htlx,nodeunnumber);
                data.put("hasRight", true);
                data.put("isEdit", true);
            }

            //如果无权限编辑或者未找到配置的编辑地址，默认查看地址
            if("".equals(url)){
                url = ContractUtil.getViewUrl(htlx);
            }
            data.put("url",url);
            apidatas.put("data", data);
            return JSON.toJSONString(R.ok(apidatas));
        } catch (Exception e) {
            LOG.error("获取合同编辑地址出错：",e);
            return JSON.toJSONString(R.error());
        }
    }

    /**
     * @description: 查询合同查看地址
     * @version: 1.0
     * @author: wanxq
     * @date: 2022年07月27 15:42:06
     * @param: [request, response]
     * @return: java.lang.String
     **/
    @GET
    @Path("/contract/getViewUrl")
    @Produces({MediaType.TEXT_PLAIN})
    public String getViewUrl(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        Map<String, Object> apidatas = new HashMap<>();
        String htlx = Util.null2String(request.getParameter("htlx"));
        String ismobile = Util.null2String(request.getParameter("ismobile"),"0");
        try {
            String viewUrl = ContractUtil.getViewUrl(htlx,ismobile);
            apidatas.put("url", viewUrl);
            return JSON.toJSONString(R.ok(apidatas));
        } catch (Exception e) {
            LOG.error("获取合同合查看地址出错：",e);
            return JSON.toJSONString(R.error());
        }
    }

    /**
     * @description: 更新用印方式
     * @version: 1.0
     * @author: wanxq
     * @date: 2022年07月28 10:11:48
     * @param: [request, response]
     * @return: java.lang.String
     **/
    @POST
    @Path("/contract/updateSealSetting")
    @Produces({MediaType.TEXT_PLAIN})
    public String updateSealSetting(@Context HttpServletRequest request, @Context HttpServletResponse response) {

        User user = HrmUserVarify.getUser(request, response);
        Map<String, Object> apidatas = new HashMap<>();
        int dataid = Util.getIntValue(request.getParameter("dataid"));
        int mainid = Util.getIntValue(request.getParameter("mainid"));
        String htlx = Util.null2String(request.getParameter("htlx"));
        int type = Util.getIntValue(request.getParameter("type"));
        String yyfs = Util.null2String(request.getParameter("yyfs"));
        String dzyyfs = Util.null2String(request.getParameter("dzyyfs"));
        String dsmdy = Util.null2String(request.getParameter("dsmdy"));
        String yqxdyr = Util.null2String(request.getParameter("yqxdyr"));
        String fwdyfs = Util.null2String(request.getParameter("fwdyfs"));
        String wlyyfs = Util.null2String(request.getParameter("wlyyfs"));
        String yyfswb = Util.null2String(request.getParameter("yyfswb"));
        String yyqksm = Util.null2String(request.getParameter("yyqksm"));
        try {
            RecordSet rs = new RecordSet();
            String jmbd = ContractUtil.getContractTableName(htlx,type);
            String updateSql = "  update "+jmbd+" set yyfs=?,dzyyfs=?"+
                    ",dsmdy=?,yqxdyr=?,fwdyfs=?,wlyyfs=?,yyfswb=?,yyqksm=? where id=? ";
            boolean result = rs.executeUpdate(updateSql,new Object[]{yyfs,dzyyfs,dsmdy,yqxdyr,fwdyfs,wlyyfs,yyfswb,yyqksm,dataid});
            if(result){
                List<Map<String,Object>> docData = ContractUtil.getContractFileData(htlx,mainid,type,user);
                apidatas.put("docData", docData);
                return JSON.toJSONString(R.ok(apidatas));
            }else {
                return JSON.toJSONString(R.error("更新用印方式失败"));
            }
        } catch (Exception e) {
            LOG.error("更新用印方式出错：",e);
            return JSON.toJSONString(R.error());
        }
    }

    /**
     * @description: 更新确认物理用印状态
     * @version: 1.0
     * @author: wanxq
     * @date: 2022年07月28 09:34:15
     * @param: [request, response]
     * @return: java.lang.String
     **/
    @POST
    @Path("/contract/updateQrwlyyStatus")
    @Produces({MediaType.TEXT_PLAIN})
    public String updateQrwlyyStatus(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        int dataid = Util.getIntValue(request.getParameter("dataid"));
        String htlx = Util.null2String(request.getParameter("htlx"));
        int type = Util.getIntValue(request.getParameter("type"));
        String qrwlyy = Util.null2String(request.getParameter("qrwlyy"));

        try {
            RecordSet rs = new RecordSet();
            String jmbd = ContractUtil.getContractTableName(htlx,type);
            String updateSql = " update "+jmbd+" set qrwlyy=? where id=? ";
            boolean result = rs.executeUpdate(updateSql,new Object[]{qrwlyy,dataid});
            if(result){
                return JSON.toJSONString(R.ok());
            }else {
                return JSON.toJSONString(R.error("更新确认物理用印状态失败"));
            }
        } catch (Exception e) {
            LOG.error("更新确认物理用印状态出错：",e);
            return JSON.toJSONString(R.error());
        }
    }

    /**
     * @description: 批量刷新用印方式
     * @version: 1.0
     * @author: wanxq
     * @date: 2022年07月28 16:17:44
     * @param: [request, response]
     * @return: java.lang.String
     **/
    @POST
    @Path("/contract/batchBrushSealWay")
    @Produces({MediaType.TEXT_PLAIN})
    public String batchBrushSealWay(@Context HttpServletRequest request, @Context HttpServletResponse response) {

        User user = HrmUserVarify.getUser(request, response);
        Map<String, Object> apidatas = new HashMap<>();
        int dataid = Util.getIntValue(request.getParameter("dataid"));
        int mainid = Util.getIntValue(request.getParameter("mainid"));
        String htlx = Util.null2String(request.getParameter("htlx"));
        int type = Util.getIntValue(request.getParameter("type"));
        String needBrushDataIds = Util.null2String(request.getParameter("needBrushDataIds"));

        try {
            RecordSet rs = new RecordSet();
            String jmbd = ContractUtil.getContractTableName(htlx,type);
            String updateSql = " update "+jmbd+" a set (a.yyfs, a.dzyyfs,a.dsmdy,a.yqxdyr,a.fwdyfs,a.wlyyfs,a.yyfswb) = " +
                    "  (select b.yyfs, b.dzyyfs,b.dsmdy,b.yqxdyr,b.fwdyfs,b.wlyyfs,b.yyfswb from "+jmbd+" b where b.id=?) where a.id in("+needBrushDataIds+") ";
            boolean result = rs.executeUpdate(updateSql,new Object[]{dataid});
            if(result){
                List<Map<String,Object>> files = ContractUtil.getContractFileData(htlx,mainid,type,user);
                apidatas.put("files", files);
                return JSON.toJSONString(R.ok(apidatas));
            }else {
                return JSON.toJSONString(R.error("批量刷新用印方式失败"));
            }
        } catch (Exception e) {
            LOG.error("批量刷新用印方式出错：",e);
            return JSON.toJSONString(R.error());

        }
    }


    /**
     * @description: 查询合同相关附件
     * @version: 1.0
     * @author: wanxq
     * @date: 2022年07月18 15:13:13
     * @param: [request, response]
     * @return: java.lang.String
     **/
    @GET
    @Path("/contract/file")
    @Produces({MediaType.TEXT_PLAIN})
    public String getContractFileData(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        User user = HrmUserVarify.getUser(request, response);
        Map<String, Object> apidatas = new HashMap<>();
        int mainid = Util.getIntValue(request.getParameter("mainid"));
        String htlx = Util.null2String(request.getParameter("htlx"));
        int type = Util.getIntValue(request.getParameter("type"));
        try {
            List<Map<String,Object>> files = ContractUtil.getContractFileData(htlx,mainid,type,user);
            apidatas.put("files", files);
            return JSON.toJSONString(R.ok(apidatas));
        } catch (Exception e) {
            LOG.error("查询合同附件出错：",e);
            return JSON.toJSONString(R.error());
        }
    }

    /**
     * @description: 查询合同信息
     * @version: 1.0
     * @author: wanxq
     * @date: 2022年07月18 10:20:42
     * @param: [request, response]
     * @return: java.lang.String
     **/
    @GET
    @Path("/contractinfo")
    @Produces({MediaType.TEXT_PLAIN})
    public String getContractInfo(@Context HttpServletRequest request, @Context HttpServletResponse response) {

        User user = HrmUserVarify.getUser(request, response);
        Map<String, Object> apidatas = new HashMap<>();

        String htlb = Util.null2String(request.getParameter("htlb"));
        String htlx = Util.null2String(request.getParameter("htlx"));
        String[] htbhs = htlb.split(",");

        List<Map<String,Object>> dataList = new ArrayList<>();
        try {
            for(int i=0;i<htbhs.length;i++){
                String htbh = htbhs[i];

                Map<String,Object> contractData = ContractUtil.getContractMainData(htbh,htlx,user);
                if(contractData.size()>0){
                    int mainid = Integer.parseInt((String) contractData.get("id"));

                    List<Map<String,Object>> docData = ContractUtil.getContractFileData(htlx,mainid,0,user);
                    contractData.put("docInfo",docData);

                    List<Map<String,Object>> attatchData = ContractUtil.getContractFileData(htlx,mainid,1,user);
                    contractData.put("attachInfo",attatchData);

                    dataList.add(contractData);
                }
            }
            apidatas.put("dataList",dataList);
            return JSON.toJSONString(R.ok(apidatas));

        } catch (Exception e) {
            LOG.error("查询合同信息出错：",e);
            return JSON.toJSONString(R.error());
        }
    }





}
