package com.dgtly.web.controller.system;

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

import com.dgtly.common.constant.UserConstants;
import com.dgtly.common.utils.security.EncryptPassWordClass;
import com.dgtly.framework.util.ShiroUtils;
import com.dgtly.system.domain.SysDept;
import com.dgtly.system.domain.SysUser;
import com.dgtly.system.service.ISysDeptService;
import com.dgtly.system.service.ISysUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.dgtly.common.annotation.Log;
import com.dgtly.common.enums.BusinessType;
import com.dgtly.system.domain.SysCompany;
import com.dgtly.system.service.ISysCompanyService;
import com.dgtly.common.core.controller.BaseController;
import com.dgtly.common.core.domain.AjaxResult;
import com.dgtly.common.utils.poi.ExcelUtil;
import com.dgtly.common.core.page.TableDataInfo;

/**
 * 公司表Controller
 * 
 * @author dgtly
 * @date 2020-01-08
 */
@Controller
@RequestMapping("/system/company")
public class SysCompanyController extends BaseController
{
    private String prefix = "system/company";

    @Autowired
    private ISysCompanyService sysCompanyService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private ISysUserService userService;

    @RequiresPermissions("system:company:view")
    @GetMapping()
    public String company()
    {
        return prefix + "/company";
    }

    /**
     * 查询公司表列表
     */
    @RequiresPermissions("system:company:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(SysCompany sysCompany)
    {
        startPage();
        List<SysCompany> list = sysCompanyService.selectSysCompanyList(sysCompany);
        return getDataTable(list);
    }

    @PostMapping("/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(SysCompany sysCompany)
    {
        int rows = sysCompanyService.updateSysCompany(sysCompany);
        if(rows>0){
            if(sysCompany.getStatus()==0){
                userService.changeStatus(sysCompany.getId(),0);
            }else if(sysCompany.getStatus()==1){
                userService.changeStatus(sysCompany.getId(),3);
            }
        }
        return AjaxResult.success();
    }

    /**
     * 导出公司表列表
     */
    @RequiresPermissions("system:company:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(SysCompany sysCompany)
    {
        List<SysCompany> list = sysCompanyService.selectSysCompanyList(sysCompany);
        ExcelUtil<SysCompany> util = new ExcelUtil<SysCompany>(SysCompany.class);
        return util.exportExcel(list, "company");
    }

    /**
     * 新增公司表
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存公司表
     */
    @RequiresPermissions("system:company:add")
    @Log(title = "公司表", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    @Transactional
    public AjaxResult addSave(SysCompany sysCompany)
    {
        SysUser localuser =  ShiroUtils.getSysUser();
        if (UserConstants.USER_NAME_NOT_UNIQUE.equals(userService.checkLoginNameUnique(sysCompany.getLoginName(),localuser.getCompanyId())))
        {
            return error("新增用户'" + sysCompany.getLoginName() + "'失败，登录账号已存在");
        }else if (sysCompany.getPassword().length() < UserConstants.PASSWORD_MIN_LENGTH
            || sysCompany.getPassword().length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            return error("密码长度为6-19，请重新设置！！");
        }else if (sysCompany.getAuthorizeId()==null)
        {
            return error("优图权限组编号不能为空！！");
        }

        int rows = sysCompanyService.insertSysCompany(sysCompany);

        if(rows>0){
            //创建公司主体部门
            SysDept dept = new SysDept();
            dept.setCompanyId(sysCompany.getId()+0l);
            dept.setDeptName(sysCompany.getCompany());
            dept.setCreateBy(localuser.getUserId().toString());
            deptService.insertDept(dept);
            //创建管理员账号
            SysUser user = new SysUser();
            user.setUserName(sysCompany.getLoginName());
            user.setSex("1");
            Long[] roles = {1l};
            user.setLoginName(sysCompany.getLoginName());
            user.setPassword(sysCompany.getPassword());
            user.setRoleIds(roles);
            user.setDeptId(dept.getDeptId());
            user.setCompanyId(sysCompany.getId()+0l);
            user.setSalt(ShiroUtils.randomSalt());
            user.setPassword(EncryptPassWordClass.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
            user.setCreateBy(ShiroUtils.getLoginName());
            rows = userService.insertUser(user);
        }
        return toAjax(rows);
    }

    /**
     * 修改公司表
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        SysCompany sysCompany = sysCompanyService.selectSysCompanyById(id);
        mmap.put("sysCompany", sysCompany);
        return prefix + "/edit";
    }

    /**
     * 修改保存公司表
     */
    @RequiresPermissions("system:company:edit")
    @Log(title = "公司表", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(SysCompany sysCompany)
    {
        return toAjax(sysCompanyService.updateSysCompany(sysCompany));
    }

    /**
     * 删除公司表
     */
    @RequiresPermissions("system:company:remove")
    @Log(title = "公司表", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(sysCompanyService.deleteSysCompanyByIds(ids));
    }
}
