package com.awspaas.user.apps.donenow_crm.controller;

import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.commons.database.RowMap;
import com.actionsoft.bpms.commons.htmlframework.HtmlPageTemplate;
import com.actionsoft.bpms.commons.mvc.view.ResponseObject;
import com.actionsoft.bpms.server.UserContext;
import com.actionsoft.bpms.server.bind.annotation.Controller;
import com.actionsoft.bpms.server.bind.annotation.Mapping;
import com.actionsoft.bpms.util.DBSql;
import com.actionsoft.sdk.local.SDK;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.awspaas.user.apps.donenow_crm.constant.CrmConstant;
import org.apache.commons.lang3.StringUtils;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class AccountController extends BaseController {
    /**
     * 删除客户
     * @param uc
     * @param ids
     * @return
     * @throws SQLException
     */
    @Mapping(value = "com.awspaas.user.apps.donenow_DelAccount")
    public ResponseObject delAccount(UserContext uc, String ids) throws SQLException {
        if (StringUtils.isBlank(ids))
            return ResponseObject.newErrResponse("请选择要删除的数据");

        String tableName = "BO_EU_DNCRM_ACCOUNT";

        //引用校验
        String result = verifyDel(tableName, ids);
        if (result != null)
            return ResponseObject.newErrResponse(result);

        Connection conn = null;
        try {
            //引用校验
            conn = DBSql.open();
            conn.setAutoCommit(false);

            for (String id : ids.split(",")) {
                BO bo = SDK.getBOAPI().get(tableName, id);
                bo.set("CLOSED", "1");
                SDK.getBOAPI().update(tableName, bo, conn);

                //Contacts联系人 删除
                List<BO> contacts = SDK.getBOAPI().query("BO_EU_DNCRM_CONTACT").addQuery("ACCOUNT_ID=", id).addQuery("CLOSED=", 0).list();
                for (BO contact : contacts) {
                    contact.set("CLOSED", "1");
                    SDK.getBOAPI().update("BO_EU_DNCRM_CONTACT", contact, conn);

                    //删除 组织中对应的用户
                    String userId = DBSql.getString(conn, "SELECT USERID FROM orguser WHERE ext5=? AND CLOSED=0 ", new Object[]{contact.getId()});
                    if (StringUtils.isNotBlank(userId))
                        SDK.getORGAPI().disabledUser(userId);//禁用组织中用户
                }

                //配置项逻辑删除
                List<BO> installedProducts = SDK.getBOAPI().query("BO_EU_DNCRM_INSTALLED_PRODUCT").addQuery("ACCOUNT_ID=", id).addQuery("CLOSED=", 0).list();
                for (BO installedProduct : installedProducts) {
                    installedProduct.set("CLOSED", "1");
                    SDK.getBOAPI().update("BO_EU_DNCRM_INSTALLED_PRODUCT", installedProduct, conn);
                }


                //客户地址
                List<BO> address = SDK.getBOAPI().query("BO_EU_DNCRM_LOCATION").addQuery("ACCOUNT_ID=", id).addQuery("CLOSED=", 0).list();
                for (BO addressBO : address) {
                    addressBO.set("CLOSED", "1");
                    SDK.getBOAPI().update("BO_EU_DNCRM_LOCATION", addressBO, conn);
                }

            }
            conn.commit();
        } catch (SQLException e) {
            e.printStackTrace();
            conn.rollback();
            return ResponseObject.newErrResponse(e.getMessage());
        } catch (Exception e) {
            return ResponseObject.newErrResponse(e.getMessage());
        } finally {
            if (conn != null)
                DBSql.close(conn);
        }
        return ResponseObject.newOkResponse();
    }


    /**
     * 删除联系人
     * @param uc
     * @param ids
     * @return
     * @throws SQLException
     */
    @Mapping(value = "com.awspaas.user.apps.donenow_DelContact")
    public ResponseObject delContact(UserContext uc, String ids) throws SQLException {
        if (StringUtils.isBlank(ids))
            return ResponseObject.newErrResponse("请选择要删除的数据");

        String tableName = "BO_EU_DNCRM_CONTACT";

        //引用校验
        String result = verifyDel(tableName, ids);
        if (result != null)
            return ResponseObject.newErrResponse(result);

        Connection conn = null;
        try {

            conn = DBSql.open();
            conn.setAutoCommit(false);

            for (String id : ids.split(",")) {
/*
            if (DBSql.getInt(conn,"SELECT COUNT(*) from BO_EU_DNSDK_TASK where contact_id=? and closed=0",new Object[]{id}) > 0)
            {
                return "该联系人是公司的外包联系人（工单中的外包人员）";
            }
*/
                if (DBSql.getInt(conn, "SELECT COUNT(*) from BO_EU_DNSDK_TASK where contact_id=? and closed=0", new Object[]{id}) > 0) {
                    throw new Exception("该联系人有关联的工单或任务");
                }

                if (DBSql.getInt(conn, "SELECT COUNT(*) from BO_EU_DNCOM_ACTIVITY where CREATEUSER=(SELECT USERID FROM orguser WHERE ext5=? AND CLOSED=0 ) and closed=0", new Object[]{id}) > 0) {
                    throw new Exception("该联系人在自助服务台创建过工单备注");
                }
/*

            if (_dal.FindSignleBySql<int>($"SELECT COUNT(*) from com_attachment where create_user_id={id} and delete_time=0") > 0)
            {
                return "该联系人在自助服务台创建过附件";
            }
*/

                if (DBSql.getInt(conn, "SELECT COUNT(*) from BO_EU_DNCTT_CONTRACT where (contact_id=? OR bill_to_contact_id=?)  and closed=0", new Object[]{id, id}) > 0) {
                    throw new Exception("该联系人是客户的账单联系人");
                }

                if (DBSql.getInt(conn, "SELECT COUNT(*) from BO_EU_DNCRM_ACCOUNT_REFERENCE where email_to_contacts=? and closed=0", new Object[]{id}) > 0) {
                    throw new Exception("该联系人是客户的唯一的一个发票邮件接收人");
                }

                //Contacts联系人 删除
                BO contact = SDK.getBOAPI().get("BO_EU_DNCRM_CONTACT", id);
                contact.set("CLOSED", "1");
                SDK.getBOAPI().update("BO_EU_DNCRM_CONTACT", contact, conn);

                //删除 组织中对应的用户
                String userId = DBSql.getString(conn, "SELECT USERID FROM orguser WHERE ext5=? AND CLOSED=0 ", new Object[]{contact.getId()});
                if (StringUtils.isNotBlank(userId))
                    SDK.getORGAPI().disabledUser(userId);//禁用组织中用户

                //配置项逻辑删除
                List<BO> installedProducts = SDK.getBOAPI().query("BO_EU_DNCRM_INSTALLED_PRODUCT").addQuery("CONTACT_ID=", id).addQuery("CLOSED=", 0).list();
                for (BO installedProduct : installedProducts) {
                    installedProduct.set("CLOSED", "1");
                    SDK.getBOAPI().update("BO_EU_DNCRM_INSTALLED_PRODUCT", installedProduct, conn);
                }
            }


            conn.commit();
        } catch (SQLException e) {
            e.printStackTrace();
            conn.rollback();
            return ResponseObject.newErrResponse(e.getMessage());
        } catch (Exception e) {
            return ResponseObject.newErrResponse(e.getMessage());
        } finally {
            if (conn != null)
                DBSql.close(conn);
        }
        return ResponseObject.newOkResponse();

    }

    /**
     * 删除配置项
     * @param uc
     * @param ids
     * @return
     * @throws SQLException
     */
    @Mapping(value = "com.awspaas.user.apps.donenow_DelInstallProd")
    public ResponseObject delInstallProd(UserContext uc, String ids) throws SQLException {

        if (StringUtils.isBlank(ids))
            return ResponseObject.newErrResponse("请选择要删除的数据");

        String tableName = "BO_EU_DNCRM_INSTALLED_PRODUCT";

        //引用校验
        String result = verifyDel(tableName, ids);
        if (result != null)
            return ResponseObject.newErrResponse(result);

        Connection conn = null;
        try {

            conn = DBSql.open();
            conn.setAutoCommit(false);

            for (String id : ids.split(",")) {

                BO installProd = SDK.getBOAPI().get(tableName, id);
                installProd.set("CLOSED", "1");
                SDK.getBOAPI().update(tableName, installProd, conn);

                //合同成本  修改项目成本
                String CONTRACT_COST_ID = installProd.getString("CONTRACT_COST_ID");
                if (StringUtils.isNotBlank(CONTRACT_COST_ID)) {
                    BO contractCost = SDK.getBOAPI().get("BO_EU_DNCTT_CONTRACT_COST", CONTRACT_COST_ID);
                    contractCost.set("CREATE_CI", "0");
                    SDK.getBOAPI().update("BO_EU_DNCRM_CONTRACT_COST", contractCost, conn);
                }

            }


            conn.commit();
        } catch (SQLException e) {
            e.printStackTrace();
            conn.rollback();
            return ResponseObject.newErrResponse(e.getMessage());
        } catch (Exception e) {
            return ResponseObject.newErrResponse(e.getMessage());
        } finally {
            if (conn != null)
                DBSql.close(conn);
        }

        return ResponseObject.newOkResponse();
    }


    /**
     * 删除地址
     * @param uc
     * @param ids
     * @return
     * @throws SQLException
     */
    @Mapping(value = "com.awspaas.user.apps.donenow_delLocation")
    public ResponseObject delLocation(UserContext uc, String ids) throws SQLException {

        if (StringUtils.isBlank(ids))
            return ResponseObject.newErrResponse("请选择要删除的数据");

        String tableName = "BO_EU_DNCRM_LOCATION";

        //引用校验
        String result = verifyDel(tableName, ids);
        if (result != null)
            return ResponseObject.newErrResponse(result);

        Connection conn = null;
        try {

            conn = DBSql.open();
            conn.setAutoCommit(false);

            for (String id : ids.split(",")) {

                BO contact = SDK.getBOAPI().get(tableName, id);
                contact.set("CLOSED", "1");
                SDK.getBOAPI().update(tableName, contact, conn);

            }

            conn.commit();
        } catch (SQLException e) {
            e.printStackTrace();
            conn.rollback();
            return ResponseObject.newErrResponse(e.getMessage());
        } catch (Exception e) {
            return ResponseObject.newErrResponse(e.getMessage());
        } finally {
            if (conn != null)
                DBSql.close(conn);
        }

        return ResponseObject.newOkResponse();
    }


    private String verifyDel(String tableName, String ids) {
        RowMap verify = DBSql.getMap("select * from BO_EU_DNSYS_DELETE_VERIFY where CODE=?", new Object[]{tableName});
        String sql = null;
        if (verify != null && StringUtils.isNotBlank(verify.getString("SEL_SQL"))) {
            sql = verify.getString("SEL_SQL");
            for (String id : ids.split(",")) {
                id = DBSql.getString("select ID from " + tableName + " where ID=?", new Object[]{id});
                String sqlById = sql.replace("**id**", "'" + id + "'");
                List<RowMap> list = DBSql.getMaps(sqlById);
                if (!list.isEmpty()) {
                    String errMsg = null;
                    for (RowMap rowMap : list) {
                        errMsg += rowMap.getString("NAME") + rowMap.getString("NUM") + "\r\n";
                    }
                    return "删除失败，被以下数据引用：\r\n" + errMsg;
                }
            }
        }
        return null;
    }

    @Mapping("com.awspaas.user.apps.donenow_crm.querydepartment")
	    public String findPchSelect(String accountId,UserContext uc) {
	       RowMap map = DBSql.getMap("SELECT * FROM orgdepartment WHERE EXT1=?", new Object[] {accountId});
	       if(map==null) {
	    	  return fail("���ȱ�����������"); 
	       }
		 return success("����ɹ�");
	      
	    }
	 
	 
	 @Mapping("com.awspaas.user.apps.donenow_crm.queryhtml")
	    public String queryhtml(String cateId,String objectId,UserContext uc) {
		 System.out.println("cateId:"+cateId);
		 System.out.println("objectId:"+objectId);

		   Map<String, Object> map = new HashMap<>();
		   map.put("uid", uc.getUID());
		   map.put("sid", uc.getSessionId());
		   map.put("cateId", cateId);
		   map.put("objectId", objectId);
		   
		   String ORGID = uc.getCompanyModel().getId();
			 System.out.println("ORGID:"+ORGID);
			 //��ѯ����������
			BO detail = SDK.getBOAPI().query(CrmConstant.BO_EU_DNSYS_UDF_GROUP).detailById(cateId);
			if(null==detail) {
				return StringUtils.EMPTY;
			}
			 //��ѯ�����������Զ����ֶΣ�����EXTTEXT5
			List<BO> fieldList = SDK.getBOAPI().query(CrmConstant.BO_EU_DNSYS_UDF_GROUP_FIELD).bindId(detail.getBindId()).list();
			List<String> list=new ArrayList<String>();
			for (BO bo : fieldList) {
				list.add("'"+bo.getString("UDF_FIELD_COL_NAME")+"'");
			}
			//����������Ϣȥ�Զ������Ա��в�ѯ�����ֶ���Ϣ������ǰ��ƴ�ӳ�ҳ��
			String fieldSql="SELECT * FROM "+CrmConstant.BO_EU_DNSYS_UDF_FIELD+" WHERE COL_NAME IN ("+org.apache.commons.lang3.StringUtils.join(list, ",")+") AND ORGID=? AND CATE_ID="+CrmConstant.PZXID+"  ORDER BY SORT_ORDER";
		   List<RowMap> udfList = DBSql.getMaps(fieldSql, new Object[] { ORGID }); 
		   System.out.println("sql2:"+fieldSql);

		   map.put("formTitle", "�������Զ����ֶ�");
		   
		   List<Map<String, Object>> colFields = new ArrayList<>();
		   
		   //��ѯ���ñ�洢����
		   BO object=SDK.getBOAPI().query(CrmConstant.BO_EU_DNCRM_INSTALLED_PRODUCT).detailById(objectId);
		   for (RowMap udf : udfList) {
		     Map<String, Object> field = new HashMap<>();
		     String COL_NAME = udf.getString("COL_NAME");
		     
		     field.put("name", COL_NAME);
		     if (object != null) {
		    	   field.put("value", object.getString(COL_NAME));
		    	     } else {
		    	     field.put("value", udf.getString("DEFAULT_VALUE"));
		    	      } 
		     String DATA_TYPE_ID = udf.getString("DATA_TYPE_ID");
		     
		     field.put("type", DATA_TYPE_ID);
		     if (DATA_TYPE_ID.equals("530")) {
		       
		       String sql = udf.getString("SQL_CONFIG");
		       
		       if (sql.contains("@")) {
		         sql = SDK.getRuleAPI().executeAtScript(sql, uc);
		       }
		       List<RowMap> list2 = DBSql.getMaps(sql, new Object[0]);
		       
		       field.put("list", list2);
		     } 
		     
		     field.put("comment", udf.getString("COL_COMMENT"));
		     field.put("readonly", udf.getString("IS_PROTECTED"));
		     field.put("required", udf.getString("IS_REQUIRED"));
		     
		     colFields.add(field);
		   } 
		   
		   map.put("colFields", JSON.toJSONString(colFields));
		   
		   return HtmlPageTemplate.merge("CONF.html", map);
		 }
	 
	 @Mapping("com.awspaas.user.apps.donenow_crm_save")
	    public ResponseObject udfSave(UserContext userContext, String cateId, String objectId, String data) throws Exception {
	      System.out.println("cateId=" + cateId + " objectId=" + objectId);
	      System.out.println(data);
	      JSONObject json = JSON.parseObject(data);
	     String set = "";
	     List<String> values = new ArrayList<>();
	     for (String key : json.keySet()) {
	      String value = json.getString(key);
	      	if(StringUtils.isBlank(value))
	      		value="";
	      	if(value.contains("[")&&value.length()>4) {
	   		 value=value.substring(2, 3);
	      	}
	         set = set + key + "=?,";
	         values.add(value);
	     } 
	     values.add(objectId);
	
	    
	     String sql = "update " + CrmConstant.BO_EU_DNCRM_INSTALLED_PRODUCT + " set " + set.substring(0, set.length() - 1) + " where id=?";
	      System.out.println("updateBO_EU_DNCRM_INSTALLED_PRODUCTSql:"+sql);

	     DBSql.update(sql, values.toArray());
	     
	     return ResponseObject.newOkResponse("����ɹ�");
   }
	 
	
}
