package com.kmall.admin.controller;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.kmall.admin.entity.PickUpCodeEntity;
import com.kmall.admin.service.PickUpCodeService;
import com.kmall.admin.utils.ParamUtils;
import com.kmall.admin.utils.ShiroUtils;
import com.kmall.common.utils.PageUtils;
import com.kmall.common.utils.Query;
import com.kmall.common.utils.R;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;


/**
 * 取货码信息表Controller
 *
 * @author emato
 * @email admin@qhdswl.com
 * @date 2020-05-19 09:11:26
 */
@Controller
@RequestMapping("pickupcode")
public class PickUpCodeController {
    @Autowired
    private PickUpCodeService pickUpCodeService;

    /**
     * 查看列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("pickupcode:list")
    @ResponseBody
    public R list(@RequestParam Map<String, Object> params) {
        ParamUtils.setName(params, "name");
        String name = (String)params.get("name");
        if(org.apache.commons.lang3.StringUtils.isNotEmpty(name)){
            params.put("orderSn", name);
        }

        //查询列表数据
        Query query = new Query(params);

        List<PickUpCodeEntity> pickUpCodeList = pickUpCodeService.queryList(query);
        int total = pickUpCodeService.queryTotal(query);

        PageUtils pageUtil = new PageUtils(pickUpCodeList, total, query.getLimit(), query.getPage());

        return R.ok().put("page", pageUtil);
    }


    @RequestMapping("/queryByPickTime")
    @RequiresPermissions("pickupcode:list")
    @ResponseBody
    public R queryByPickTime(@RequestParam Map<String, Object> params) {
        String pickTime = (String)params.get("pickTime");
        //有日期检查格式，没有生成当天日期
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(pickTime)){
            try{
                String regEx = "\\d{4}(\\-)\\d{2}\\1\\d{2}";
                // 编译正则表达式
                Pattern pattern = Pattern.compile(regEx);
                Matcher matcher = pattern.matcher(pickTime);
                // 字符串是否与正则表达式相匹配
                boolean rs = matcher.matches();

                if (!rs){
                    throw new Exception();
                }
            }catch(Exception e){
                return R.error("传入日期格式错误，请修改日期格式为'yyyy-MM-dd'!");
            }
        } else {
            DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            pickTime = formatter.format(new Date());
        }
        params.put("pickUpCodeCreatetime", pickTime);

        //查询列表数据
        Query query = new Query(params);

        List<PickUpCodeEntity> pickUpCodeList = pickUpCodeService.queryList(query);
        int total = pickUpCodeService.queryTotal(query);

        PageUtils pageUtil = new PageUtils(pickUpCodeList, total, query.getLimit(), query.getPage());

        return R.ok().put("page", pageUtil);
    }

    /**
     * 查看信息
     */
    @RequestMapping("/info/{orderSn}")
    @RequiresPermissions("pickupcode:info")
    @ResponseBody
    public R info(@PathVariable("orderSn") String orderSn) {
        PickUpCodeEntity pickUpCode = pickUpCodeService.queryObject(orderSn);

        return R.ok().put("pickUpCode", pickUpCode);
    }

    /**
     * 生成取货码
     */
    @RequestMapping("/save")
    @RequiresPermissions("pickupcode:save")
    @ResponseBody
    public R save(@RequestBody PickUpCodeEntity pickUpCode) {
        if(org.apache.commons.lang3.StringUtils.isEmpty(pickUpCode.getOrderSn())){
            return R.error("订单编号为空！");
        }

        //生成一个 5 位的随机字符串
        String randomCode = RandomStringUtils.randomAlphanumeric(5).toUpperCase();
        //K： 跨境电商 ， Y：一般贸易
        pickUpCode.setPickUpCodeSn("K-"+randomCode);
        //  pickUpCode.setPickUpCodeSn("Y-");
        pickUpCode.setPickUpCodeStatus("0");
        if (pickUpCode.getPickUpCodeCreatetime()==null){
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
            pickUpCode.setPickUpCodeCreatetime(df.format(new Date()));// new Date()为获取当前系统时间
        }
        pickUpCode.setModerSn(ShiroUtils.getUserEntity().getUserId().toString());
        pickUpCode.setCreateTime(new Date());
        pickUpCode.setModTime(new Date());


        int result = pickUpCodeService.save(pickUpCode);
        if (result <= 0 ){
            return R.error("生成取货码失败！");
        }

        return R.ok().put("pickUpCode",pickUpCode );
    }

    /**
     * 取货码核销
     */
    @RequestMapping("/verification")
    @RequiresPermissions("pickupcode:update")
    @ResponseBody
    public R Verification(@RequestBody PickUpCodeEntity pickUpCode) {
        if(org.apache.commons.lang3.StringUtils.isEmpty(pickUpCode.getOrderSn())){
            return R.error("订单编号为空！");
        }

        String status = pickUpCodeService.queryPickUpCodeStatus(pickUpCode.getOrderSn());
        if(status.equals("1")){
            return R.error("取货码已核销过！");
        }

        pickUpCode.setPickUpCodeStatus("1");
        if (pickUpCode.getPickUpCodeCreatetime()==null){
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
            pickUpCode.setPickUpCodeVerificationtime(df.format(new Date()));// new Date()为获取当前系统时间
        }
        pickUpCode.setModerSn(ShiroUtils.getUserEntity().getUserId().toString());
        pickUpCode.setModTime(new Date());

        int result = pickUpCodeService.update(pickUpCode);
        if (result <= 0 ){
            return R.error("取货码核销失败！");
        }
        PickUpCodeEntity pickUpCodeEntity = pickUpCodeService.queryObject(pickUpCode.getOrderSn());

        return R.ok().put("pickUpCode",pickUpCodeEntity );
    }


    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("pickupcode:delete")
    @ResponseBody
    public R delete(@RequestBody String[]orderSns) {
        int result = pickUpCodeService.deleteBatch(orderSns);

        return R.ok().put("result", result);
    }

    /**
     * 查看所有列表
     */
    @RequestMapping("/queryAll")
    @ResponseBody
    public R queryAll(@RequestParam Map<String, Object> params) {

        List<PickUpCodeEntity> list = pickUpCodeService.queryList(params);

        return R.ok().put("list", list);
    }
}
