package com.fs.company.controller;

import cn.hutool.core.util.IdUtil;
import com.fs.common.annotation.Log;
import com.fs.common.annotation.RepeatSubmit;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.domain.R;
import com.fs.common.core.domain.model.LoginUser;
import com.fs.common.core.page.TableDataInfo;
import com.fs.common.enums.BusinessType;
import com.fs.common.utils.SecurityUtils;
import com.fs.common.utils.ServletUtils;
import com.fs.common.utils.StringUtils;
import com.fs.common.utils.poi.ExcelUtil;
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.utils.OrderCodeUtils;
import com.fs.framework.web.service.TokenService;
import com.fs.his.vo.OptionsVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 企业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)
    {
        startPage();
        List<CompanyVO> list = companyService.selectCompanyVOList(param);
        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()));
        company.setOmsCode("SF.1");
        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);
                caller.setBindTime(null);
                callerService.updateCompanyVoiceCaller(caller);
            }
        }
        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(),SecurityUtils.encryptPassword("123456")));
    }

//    @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 =  OrderCodeUtils.getOrderSn();
        if(StringUtils.isEmpty(orderSn)){
            return R.error("订单生成失败，请重试");
        }
        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 =  OrderCodeUtils.getOrderSn();
        if(StringUtils.isEmpty(orderSn)){
            return R.error("订单生成失败，请重试");
        }
        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("提交成功,等待审核");
    }

    @GetMapping("/allList")
    public TableDataInfo getHospital()
    {
        List<OptionsVO> list = companyService.selectAllCompanyList();
        return getDataTable(list);
    }
}
