package com.willalp.web.controller.apply;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.willalp.apply.domain.HsSysApply;
import com.willalp.apply.service.IHsSysApplyService;
import com.willalp.common.annotation.Log;
import com.willalp.common.core.controller.BaseController;
import com.willalp.common.core.domain.AjaxResult;
import com.willalp.common.core.page.TableDataInfo;
import com.willalp.common.enums.BusinessType;
import com.willalp.common.utils.DateUtils;
import com.willalp.common.utils.SecurityUtils;
import com.willalp.common.utils.poi.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 编码申请Controller
 *
 * @author bjh
 * @date 2022-01-04
 */
@RestController
@RequestMapping("/apply/apply")
public class HsSysApplyController extends BaseController
{
    @Autowired
    private IHsSysApplyService hsSysApplyService;

    /**
     * 查询编码申请列表
     */
    @PreAuthorize("@ss.hasPermi('apply:apply:list')")
    @GetMapping("/list")
    public TableDataInfo list(HsSysApply hsSysApply)
    {
        startPage();
        List<HsSysApply> list = hsSysApplyService.selectHsSysApplyList(hsSysApply);
        return getDataTable(list);
    }

    /**
     * 导出编码申请列表
     */
    @PreAuthorize("@ss.hasPermi('apply:apply:export')")
    @Log(title = "编码申请", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(HsSysApply hsSysApply)
    {
        List<HsSysApply> list = hsSysApplyService.selectHsSysApplyList(hsSysApply);
        ExcelUtil<HsSysApply> util = new ExcelUtil<HsSysApply>(HsSysApply.class);
        return util.exportExcel(list, "编码申请数据");
    }

    /**
     * 获取编码申请详细信息
     */
    @PreAuthorize("@ss.hasPermi('apply:apply:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(hsSysApplyService.getById(id));
    }

    /**
     * 新增编码申请
     */
    @PreAuthorize("@ss.hasPermi('apply:apply:add')")
    @Log(title = "编码申请", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody HsSysApply hsSysApply)
    {
        while (true) {
            String idStr = IdWorker.getIdStr();
            HsSysApply byId = hsSysApplyService.getById(idStr);
            if (null == byId) {
                hsSysApply.setId(idStr);
                break;
            }
        }
        hsSysApply.setCreateBy(SecurityUtils.getUsername());
        hsSysApply.setCreateTime(DateUtils.getNowDate());
        String codeid = hsSysApply.getCodeid();
        Map<String,Object> syscode = hsSysApplyService.selectCodeById(Long.valueOf(codeid));
        String shcode = ""; //层级编码
        int parentid = 1;
        String levelid = syscode.get("levelid")+"";
        while( parentid!=0){
            List<Map<String,Object>> syslevel = hsSysApplyService.selectHsSysLevelList(levelid); //层级信息
            if(syslevel.size()>0){
                shcode = syslevel.get(0).get("levelcode") + shcode;
            }
            parentid = syslevel.get(0).get("parent_id")==null?0: Integer.valueOf(syslevel.get(0).get("parent_id")+"");
            levelid = parentid+"";
        }

        for(int i=1 ;i<10 ;i++){
            String codeid1 = syscode.get("codeid"+String.valueOf(i))+"";
            String name1 = syscode.get("name"+String.valueOf(i))+"";
            String length1 = syscode.get("length"+String.valueOf(i))+"";
            String codeid_new = getValue(codeid1,name1,length1,codeid);
            hsSysApplyService.updateSysCodename(codeid,i,codeid_new);
            shcode = shcode+codeid_new;
        }
        List<Map<String,Object>> list = hsSysApplyService.checkApplyData(shcode);
        if(list.size()>0){
            return AjaxResult.error("申请失败，相同编码已存在：" + shcode );
        }
        hsSysApply.setCodeapply(shcode);
        return toAjax(hsSysApplyService.save(hsSysApply));
    }

    public String getValue(String value,String ex,String length,String codeid){ //sys_code -codeid1234,codename,id
        HsSysApply hsSysApply = new HsSysApply();
        hsSysApply.setCodeid(codeid);
        List<HsSysApply> list = hsSysApplyService.selectHsSysApplyList(hsSysApply);
        switch (value) {
            case "null":
                ex = "";
                break;
            case "1":
                ex = ex;
                break;
            case "2":
                ex = ex;
                break;
            case "3":
                ex = ex;
                break;
            case "4"://累计数（长累计）
                if(list.size()>0){
                    ex = String.format("%0"+ex.length()+"d", Integer.parseInt(ex)+1);
                }else{
                    ex = ex;
                }
                break;
            case "5"://随机
                StringBuffer rad = new StringBuffer("1");
                while(Integer.valueOf(length)>1){
                    rad.append(0);
                    length = String.valueOf(Integer.valueOf(length)-1);
                }
                ex = Math.round((Math.random()*9) * Integer.valueOf(rad.toString()))+"";
                break;
            case "6"://年月日
                Date date = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                ex = sdf.format(date);
                break;
            case "7"://流水
                if(list.size()>0){
                    ex = String.format("%0"+ex.length()+"d", Integer.parseInt(ex)+1);
                }else{
                    ex = ex;
                }
                break;
            case "8"://累计数（按日）
                if(list.size()>0){
                    Date date1 = new Date();
                    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd");
                    String currentdate = sdf1.format(date1);
                    String createtime = sdf1.format(list.get(0).getCreateTime());
                    if(currentdate.equals(createtime)){
                        ex = String.format("%0"+ex.length()+"d", Integer.parseInt(ex)+1);
                    }else{
                        ex = String.format("%0"+ex.length()+"d",1);
                    }
                }else{
                    ex = ex;
                }
                break;
            case "9":
                ex = ex;
                break;
            default:
                throw new IllegalStateException("Unexpected value: " + value);
        }
        return ex;
    }

    /**
     * 修改编码申请
     */
    @PreAuthorize("@ss.hasPermi('apply:apply:edit')")
    @Log(title = "编码申请", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody HsSysApply hsSysApply)
    {
        hsSysApply.setUpdateBy(SecurityUtils.getUsername());
        hsSysApply.setUpdateTime(DateUtils.getNowDate());
        return toAjax(hsSysApplyService.updateById(hsSysApply));
    }

    /**
     * 删除编码申请
     */
    @PreAuthorize("@ss.hasPermi('apply:apply:remove')")
    @Log(title = "编码申请", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(hsSysApplyService.removeByIds(Arrays.asList(ids)));
    }
}
