package com.fs.company.controller;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import cn.hutool.core.util.IdUtil;
import com.fs.common.annotation.RepeatSubmit;
import com.fs.common.core.domain.R;
import com.fs.common.utils.OrderUtils;
import com.fs.common.utils.ParseUtils;
import com.fs.common.utils.ServletUtils;
import com.fs.common.utils.sign.Md5Utils;
import com.fs.company.domain.*;
import com.fs.company.param.CompanyDeductParam;
import com.fs.company.param.CompanyParam;
import com.fs.company.param.CompanyRechargeParam;
import com.fs.company.param.CompanyVoiceCallerParam;
import com.fs.company.service.*;
import com.fs.company.vo.CompanyCrmVO;
import com.fs.company.vo.CompanyVO;
import com.fs.company.vo.CompanyVoiceCallerListVO;
import com.fs.core.security.LoginUser;
import com.fs.core.security.SecurityUtils;
import com.fs.core.web.service.TokenService;
import lombok.Synchronized;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fs.common.annotation.Log;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.enums.BusinessType;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.common.core.page.TableDataInfo;

import javax.swing.*;

/**
 * 企业Controller
 *
 * @author fs
 * @date 2021-10-04
 */
@RestController
@RequestMapping("/company/company")
public class CompanyController extends BaseController
{
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ICompanyService companyService;
    @Autowired
    private ICompanyUserService userService;
    @Autowired
    private ICompanyRechargeService rechargeService;
    @Autowired
    private ICompanyDeductService deductService;
    @Autowired
    private ICompanyVoiceCallerService callerService;
    /**
     * 查询企业列表
     */
    @PreAuthorize("@ss.hasPermi('company:company:list')")
    @GetMapping("/list")
    public TableDataInfo list(CompanyParam param) throws ParseException {
        startPage();
        List<CompanyVO> list = companyService.selectCompanyVOList(param);
        for (CompanyVO vo : list){
            vo.setCompanyMobile(ParseUtils.parsePhone(vo.getCompanyMobile()));
        }
        return getDataTable(list);
    }

    /**
     * 导出企业列表
     */
    @PreAuthorize("@ss.hasPermi('company:company:export')")
    @Log(title = "企业", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(CompanyParam company)
    {
        List<CompanyVO> list = companyService.selectCompanyVOList(company);
        ExcelUtil<CompanyVO> util = new ExcelUtil<CompanyVO>(CompanyVO.class);
        return util.exportExcel(list, "company");
    }

    /**
     * 获取企业详细信息
     */
    @PreAuthorize("@ss.hasPermi('company:company:query')")
    @GetMapping(value = "/{companyId}")
    public AjaxResult getInfo(@PathVariable("companyId") Long companyId)
    {
        return AjaxResult.success(companyService.selectCompanyById(companyId));
    }

    /**
     * 新增企业
     */
    @PreAuthorize("@ss.hasPermi('company:company:add')")
    @Log(title = "企业", businessType = BusinessType.INSERT)
    @PostMapping
    public R add(@RequestBody Company company)
    {
        company.setPassword(SecurityUtils.encryptPassword(company.getPassword()));
        company.setAppId(Md5Utils.hash(company.getUserName()));
        company.setAppKey(Md5Utils.hash(company.getPassword()));
        return companyService.insertCompany(company);
    }

    /**
     * 修改企业
     */
    @PreAuthorize("@ss.hasPermi('company:company:edit')")
    @Log(title = "企业", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Company company)
    {
        CompanyUser companyUser = new CompanyUser();
        if (company.getStatus()==0){
            companyUser.setStatus("1");
            companyUser.setCompanyId(company.getCompanyId());
//            companyUser.setUserType("00");
            userService.updateAllCompanyUser(companyUser);
            CompanyVoiceCallerParam param = new CompanyVoiceCallerParam();
            param.setCompanyId(company.getCompanyId());
            List<CompanyVoiceCallerListVO> list = callerService.selectCompanyVoiceCallerListVO(param);
            for (CompanyVoiceCallerListVO vo : list){
                CompanyVoiceCaller caller=callerService.selectCompanyVoiceCallerById(vo.getCallerId());
                caller.setCompanyId(0L);
                caller.setCompanyUserId(0L);
                caller.setMobile("");
                caller.setStatus(1);
                callerService.updateCompanyVoiceCaller(caller);
            }
        }else {
            CompanyUser companyUser1 = userService.selectCompanyUserAdminByCompanyId(company.getCompanyId());
            companyUser1.setStatus("0");
            userService.updateCompanyUser(companyUser1);
        }
        return toAjax(companyService.updateCompany(company));
    }



    /**
     * 删除企业
     */
    @PreAuthorize("@ss.hasPermi('company:company:remove')")
    @Log(title = "企业", businessType = BusinessType.DELETE)
	@DeleteMapping("/{companyIds}")
    public AjaxResult remove(@PathVariable Long[] companyIds)
    {
        return toAjax(companyService.deleteCompanyByIds(companyIds));
    }

    @GetMapping("/getCompanyList")
    public R getCompanyList()
    {
        Company map=new Company();
        map.setIsDel(0);
        List<Company> list = companyService.selectCompanyList(map);
        return R.ok().put("data",list);
    }

//  @PreAuthorize("@ss.hasPermi('company:company:crmDayCountlist')")
    @GetMapping("/crmDayCountlist")
    public TableDataInfo companyCrmDayCountList(CompanyParam param)
    {
        startPage();
        List<CompanyCrmVO> list = companyService.selectCompanyCrmDayCountList(param);
        return getDataTable(list);
    }



    @PreAuthorize("@ss.hasPermi('company:company:resetPwd')")
    @PostMapping("/resetPwd/{companyId}")
    public AjaxResult resetPwd(@PathVariable Long companyId)
    {
        Company company=companyService.selectCompanyById(companyId);
        return toAjax(userService.resetUserPwdByUserId(company.getUserId(),"$2a$10$PYuQ7.6jxFlh5qRaDCsBzuIjQFYAFEQfmRFM5yj0Wd4/GE3hqRgZq"));
    }

//    @PreAuthorize("@ss.hasPermi('company:company:resetMoney')")
//    @PostMapping("/resetMoney/{companyId}")
//    public R resetMoney(@PathVariable Long companyId)
//    {
//        //companyService.resetMoney(companyId);
//        return R.ok("功能已停用");
//    }


    @PreAuthorize("@ss.hasPermi('company:company:recharge')")
    @Log(title = "企业转账", businessType = BusinessType.INSERT)
    @PostMapping(value = "/recharge")
    @Transactional
    @RepeatSubmit
    public R recharge(@RequestBody CompanyRechargeParam param)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        CompanyRecharge recharge=new CompanyRecharge();
        String orderSn = IdUtil.getSnowflake(0, 0).nextIdStr();
        recharge.setRechargeNo(orderSn);
        recharge.setCompanyId(param.getCompanyId());
        recharge.setMoney(param.getMoney());
        recharge.setCreateUserId(loginUser.getUser().getUserId());
        recharge.setIsAudit(0);
        recharge.setStatus(0);
        recharge.setRemark(param.getRemark());
        recharge.setPayType(3);
        rechargeService.insertCompanyRecharge(recharge);
        return R.ok("提交成功,等待审核");

    }

    @PreAuthorize("@ss.hasPermi('company:company:deduct')")
    @Log(title = "企业扣款", businessType = BusinessType.INSERT)
    @PostMapping(value = "/deduct")
    @Transactional
    @RepeatSubmit
    public R deduct(@RequestBody CompanyDeductParam param)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        CompanyDeduct deduct=new CompanyDeduct();
        String orderSn = IdUtil.getSnowflake(0, 0).nextIdStr();
        deduct.setDeductNo(orderSn);
        deduct.setCompanyId(param.getCompanyId());
        deduct.setMoney(param.getMoney());
        deduct.setCreateUserId(loginUser.getUser().getUserId());
        deduct.setIsAudit(0);
        deduct.setRemark(param.getRemark());
        deductService.insertCompanyDeduct(deduct);
        return R.ok("提交成功,等待审核");
    }


}
