package com.sifang.modules.customer.Service;

import com.google.common.collect.Maps;
import com.jfinal.kit.HashKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.constant.SourceConstants;
import com.sifang.modules.customer.constant.UserConstants;
import com.sifang.modules.customer.dao.CustomerDao;
import com.sifang.modules.customer.dao.PowerStationDao;
import com.sifang.modules.customer.dao.SendedSmsDao;
import com.sifang.modules.customer.entity.Customer;
import com.sifang.modules.customer.entity.PowerStation;
import com.sifang.modules.sunshine.SystemSetting.utils.BusinessException;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.common.utils.DateUtils;
import com.sifang.modules.sys.common.utils.IdGen;
import com.sifang.modules.sys.common.utils.StringUtil;
import com.sifang.modules.sys.util.LayuiPage;

import com.sifang.modules.sys.util.SfSmsUtils;
import org.hibernate.SQLQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class CustomerService extends BaseService {
    @Autowired
    CustomerDao customerDao;
    @Autowired
    private PowerStationDao powerStationDao;

    @Autowired
    private SendedSmsDao sendedSmsDao;

    public void getCustomerList(LayuiPage<Record> page, Map<String, String> map) {
        List<Record> list = customerDao.getCustomerList(page, map);
        page.setData(list);
    }

    public List<Record> getCustomerLists() {
        List<Record> list = customerDao.getCustomerList(null, null);
        return list;
    }

    public Record getPsDetail(String id) {
        String sql = "select * from crm_power_station s  where s.id = ?";
        Record record = Db.findFirst(sql, id);
        return record;
    }

    /**
     * 获取电站下的设备信息
     */
    public List<Record> getStationDevice(String powId, String userId) {
        return Db.find("SELECT * FROM crm_power_station_device a WHERE a.power_station_id =? AND a.user_id=? and status='1'", powId, userId);
    }


  /*  public Record getWarrantyCard(String name) {
        String sql = "select * from crm_order o  where o.power_station_name = ? and o.service_type = '安装' LIMIT 1 ";
        Record record = Db.findFirst(sql,name);
        return record;
    }*/

    //根据工单id获取保修卡中的信息
    public List<Record> getWarranty(String orderId) {
        String sql = " SELECT * FROM `crm_customer_warranty_card` WHERE order_id=? ";
        return Db.find(sql, orderId);
    }

    public List<Record> getImgs(String id) {
        String sql = "select d.* from crm_power_station s left join crm_power_station_imgs d on s.id = d.power_station_id  where s.id = ?";
        List<Record> list = Db.find(sql, id);
        return list;
    }

    public Customer getCustomerByUserId(String userId) {
        return customerDao.getCustomerBuserId(userId);
    }


    @Transactional(rollbackFor = Exception.class)
    public String CustomerRegister(Map<String, String> map) {
        String mobile = map.get("mapbile");
        long count = customerDao.getCustimerByMoblie(mobile, "");
        if (count > 0) {
            //该手机号已存在
            return "502";
        }
        Customer cus = new Customer();
        cus.setUserId(IdGen.uuid());
        cus.setMobileTel(map.get("mobile"));
        cus.setUserAccount(map.get("mobile"));
        cus.setPassword(HashKit.md5(map.get("password")));
        cus.setUserType(UserConstants.USER_TYPE_TWO);
        cus.setStatus(UserConstants.STATUS_USE);
        cus.setLoginTimes("0");
        cus.setDisableTime(DateUtils.formatDateTime(new Date()));
        customerDao.save(cus);
        PowerStation pow = new PowerStation();
        pow.setPsName(map.get("psName"));
        pow.setPsId(cus.getId());
        pow.setPsStatus(SourceConstants.STATUS_ZERO);
        pow.setContactName(map.get("mobile"));
        pow.setProvince(map.get("province"));
        pow.setCity(map.get("city"));
        pow.setArea(map.get("area"));
        pow.setLocation(map.get("address"));
        pow.setUserId(cus.getUserId());
        pow.setUserMobleTel(map.get("mobile"));
        powerStationDao.save(pow);

        return "200";
    }

    public long checkMobile(String mobile, String userType) {
        return customerDao.getCustimerByMoblie(mobile, userType);
    }

    public Record getpowerStation(String mobile) {
        String sql = "select * from crm_customer s  where s.user_account = ? and s.user_type ='2' and s.status ='1' ";
        Record record = Db.findFirst(sql, mobile);
        return record;
    }

    public void UpdateCustomer(String Id) {
        SQLQuery sqlQuery = customerDao.getSession().createSQLQuery("UPDATE crm_customer SET login_times = login_times +1 , login_last_date =:date  WHERE  id=:ids");
        sqlQuery.setParameter("date", DateUtils.getDateTime());
        sqlQuery.setParameter("ids", Id);
        sqlQuery.executeUpdate();
    }

    public void ProhibitCustomer(String id) {
        Customer cus = customerDao.get(id);
        cus.setStatus(UserConstants.STATUS_DISABLED);
        customerDao.save(cus);

    }


    /**
     * 获取短信验证码
     * 点击获取验证码按钮---获取验证码
     */
    public String sendingMobile(String mobile, String code) {
        try {
            String boo = SfSmsUtils.sendCode(mobile, code);
            if (StringUtil.isBlank(boo)) {
                return "201";
            }
            return "200";

        } catch (Exception e) {
            e.printStackTrace();
            return "201";
        }

    }

    /**
     * 修改密码
     */
    public Object updatePasswork(String mobile, String password, String newPassword, String userId) {
        Map<String, Object> maps = Maps.newHashMap();
        if (StringUtil.isBlank(newPassword)) {
            maps.put("code", "203");
            maps.put("data", "新密码为空");
            maps.put("msg", "新密码为空");
            return maps;
        }
        String passwords = HashKit.md5(password);
        Customer cus = customerDao.getCustomerBuserId(userId);
        if (cus != null) {
            String lodPass = cus.getPassword();
            if (!lodPass.equals(passwords)) {
                maps.put("code", "201");
                maps.put("data", "原密码错误");
                maps.put("msg", "原密码错误");
                return maps;
            }
            cus.setPassword(HashKit.md5(newPassword));
            customerDao.save(cus);
            maps.put("code", "200");
            maps.put("data", "修改密码成功");
            maps.put("msg", "");
        } else {
            maps.put("code", "202");
            maps.put("data", "修改密码失败");
            maps.put("msg", "修改密码失败");
        }
        return maps;
    }

    /**
     * 忘记密码，重置
     */
    public void ResetPassword(String moblie, String password) {
        SQLQuery sqlQuery = customerDao.getSession().createSQLQuery("update crm_customer a set a.password=:password where a.mobile_tel=:moblie and a.user_type = '2' ");
        sqlQuery.setParameter("password", password);
        sqlQuery.setParameter("moblie", moblie);
        sqlQuery.executeUpdate();

    }

    public void ResetTraderPassword(String moblie, String password) {
        SQLQuery sqlQuery = customerDao.getSession().createSQLQuery("update sys_user a set a.password=:password where a.mobile=:moblie  ");
        sqlQuery.setParameter("password", password);
        sqlQuery.setParameter("moblie", moblie);
       int cou = sqlQuery.executeUpdate();
       if(cou<1){
           throw new BusinessException("修改密码失败 ");
       }

    }


    public void updateRemark(String id, String remark) {

        customerDao.updateRemark(id, remark);
    }
    @Transactional(rollbackFor = Exception.class)
    public String sendBwMsg(String mobile,String name,String address,String num,String spec,String model,String total) {
        try {
            String boo = SfSmsUtils.sendBWMsg(mobile, name,address, num, spec, model, total);
            if (StringUtil.isBlank(boo)) {
                return "201";
            }
            return "200";
        } catch (Exception e) {
            e.printStackTrace();
            return "201";
        }
    }

}
