package com.fs.hisStore.controller.store;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.fs.common.annotation.Log;
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.page.TableDataInfo;
import com.fs.common.enums.BusinessType;
import com.fs.common.utils.ServletUtils;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.framework.service.TokenServiceScrm;
import com.fs.his.param.FsStoreProductListSParam;
import com.fs.his.vo.FsStoreProductExcelVO;
import com.fs.his.vo.FsStoreProductListSVO;
import com.fs.his.vo.OptionsVO;
import com.fs.hisStore.domain.*;
import com.fs.hisStore.param.FsStoreProductAddEditParam;
import com.fs.hisStore.service.IFsStoreProductAttrScrmService;
import com.fs.hisStore.service.IFsStoreProductScrmService;
import com.fs.hisStore.utils.StoreAuditLogUtil;
import com.fs.hisStore.utils.UserUtil;
import com.fs.hisStore.vo.FsStoreProductListVO;
import com.fs.store.vo.FsStoreProductStoreExcelVO;
import com.mysql.cj.util.StringUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * 商品Controller
 *
 * @author fs
 * @date 2023-06-08
 */
@RestController
@RequestMapping("/store/store/storeProduct")
public class FsStoreProductScrmController extends BaseController
{
    @Autowired
    private IFsStoreProductScrmService fsStoreProductService;

    @Autowired
    private IFsStoreProductAttrScrmService attrService;

    @Autowired
    private TokenServiceScrm tokenService;

    @Autowired
    private StoreAuditLogUtil storeAuditLogUtil;


    /**
     * 商品关键字检查
     * 只要商品关键字在数据库中存在，就不允许添加商品。
     * @param keyWords
     * @return
     */
    @Log(title = "商品管理", businessType = BusinessType.AUDIT, isStoreLog = true, logParam = {"商品", "商品关键字检查"})
    @GetMapping("/selectForbiddenKeywords/{keyWords}")
    public R selectForbiddenKeywords(@PathVariable("keyWords")String keyWords) {
        if(org.apache.commons.lang3.StringUtils.isEmpty(keyWords))return R.ok().put("data", true);
        List<ForbiddenOnlineMedicine> list = fsStoreProductService.selectForbiddenKeywords(keyWords);
        if(CollectionUtils.isEmpty(list)){
            return R.ok().put("data", true);
        }else{
            return R.ok().put("data", false).put("msg", list.get(0).getModule());
        }
    }

    /**
     * 判断该药店的经营许可证是否允许上架该商品
     * @param fsStoreProduct
     */
    @Log(title = "商品管理", businessType = BusinessType.AUDIT, isStoreLog = true, logParam = {"商品", "判断该药店的经营许可证是否允许上架该商品"})
    @PostMapping("/checkStoreDrugLicense")
    public R checkStoreDrugLicense(@RequestBody FsStoreProductAddEditParam fsStoreProduct) {
        StoreLoginUserScrm loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        fsStoreProduct.setStoreId(loginUser.getFsStore().getStoreId());
        return R.ok().put("data", fsStoreProductService.checkStoreDrugLicense(fsStoreProduct.getStoreId(), fsStoreProduct.getCateId(),
                org.apache.commons.lang3.StringUtils.isEmpty(fsStoreProduct.getMedicalDeviceCode())?null:fsStoreProduct.getMedicalDeviceCode()));
    }


    /**
     * 查询商品列表
     * @param fsStoreProduct
     * @return
     */
    @GetMapping("/list")
    public TableDataInfo list(FsStoreProductScrm fsStoreProduct)
    {
        startPage();
        List<FsStoreProductListVO> list;
        StoreLoginUserScrm loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        fsStoreProduct.setStoreId(loginUser.getFsStore().getStoreId());
        if(StringUtils.isNullOrEmpty(fsStoreProduct.getBarCode())){
            list = fsStoreProductService.selectFsStoreProductListVO(fsStoreProduct);
        }else{
            list = fsStoreProductService.selectFsStoreProductBarCodeListVO(fsStoreProduct);
        }
        return getDataTable(list);
    }


    /**
     * 导出商品列表
     */
    @Log(title = "商品", businessType = BusinessType.EXPORT,isStoreLog = true,logParam = {"商品","导出商品信息"})
    @GetMapping("/export")
    public AjaxResult export(FsStoreProductScrm fsStoreProduct)
    {
        fsStoreProduct.setStoreId(UserUtil.getLoginUserStoreID());
        List<FsStoreProductScrm> list = fsStoreProductService.selectFsStoreProductList(fsStoreProduct);
        ExcelUtil<FsStoreProductScrm> util = new ExcelUtil<FsStoreProductScrm>(FsStoreProductScrm.class);
        return util.exportExcel(list, "商品数据");
    }

    @Log(title = "商品导入", businessType = BusinessType.IMPORT,isStoreLog = true,logParam = {"商品","导入商品信息"})
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<FsStoreProductExcelVO> util = new ExcelUtil<>(FsStoreProductExcelVO.class);
        List<FsStoreProductExcelVO> list = util.importExcel(file.getInputStream());
        for (FsStoreProductExcelVO fsStoreProductExcelVO : list) {
            fsStoreProductExcelVO.setStoreId(UserUtil.getLoginUserStoreID());
        }
        String message = fsStoreProductService.importSrorePeoduct(list, updateSupport);
        return AjaxResult.success(message);
    }

    @GetMapping("/importTemplate")
    public AjaxResult importTemplate()
    {
        ExcelUtil<FsStoreProductStoreExcelVO> util = new ExcelUtil<>(FsStoreProductStoreExcelVO.class);
        return util.importTemplateExcel("商品数据");
    }

    @PostMapping("/price/{price}")
    public AjaxResult editPrice(@RequestBody FsStoreProductScrm fsStoreProduct, @PathVariable("price")Integer price)
    {
        fsStoreProduct.setStoreId(UserUtil.getLoginUserStoreID());
        return toAjax(fsStoreProductService.updateFsStoreProductPrice(fsStoreProduct,price));
    }
    /**
     * 新增商品
     */

    @Log(title = "商品", businessType = BusinessType.INSERT,isStoreLog = true,logParam = {"商品","新增商品信息"})
    @PostMapping
    public AjaxResult add(@RequestBody FsStoreProductScrm fsStoreProduct)
    {
        fsStoreProduct.setStoreId(UserUtil.getLoginUserStoreID());
        return toAjax(fsStoreProductService.insertFsStoreProduct(fsStoreProduct));
    }

    /**
     * 修改商品
     */

    @Log(title = "商品", businessType = BusinessType.UPDATE,isStoreLog = true,logParam = {"商品","修改商品信息"})
    @PutMapping
    public AjaxResult edit(@RequestBody FsStoreProductScrm fsStoreProduct)
    {
        return toAjax(fsStoreProductService.updateFsStoreProduct(fsStoreProduct));
    }

    /**
     * 删除商品
     */

    @Log(title = "商品", businessType = BusinessType.DELETE,isStoreLog = true,logParam = {"商品","批量删除商品信息"})
	@DeleteMapping("/{productIds}")
    public R remove(@PathVariable Long[] productIds)
    {

        return fsStoreProductService.deleteFsStoreProductByIds(productIds);
    }


    /**
     * 获取商品商家列表
     */
    @GetMapping("/storeList")
    public TableDataInfo storeList()
    {
        List<OptionsVO> list = fsStoreProductService.selectFsStoreProductStoreList();
        return getDataTable(list);
    }

    @ApiOperation(value = "生成属性")
    @PostMapping(value = "/genFormatAttr/{productId}")
    public ResponseEntity genFormatAttr(@PathVariable Long productId, @RequestBody String jsonStr,Long[] stores){

        return new ResponseEntity<>(fsStoreProductService.getFormatAttr(productId,jsonStr, stores), HttpStatus.OK);
    }
    /**
     * 获取商品详细信息
     */

    @GetMapping(value = "/{productId}")
    public R getInfo(@PathVariable("productId") Long productId)
    {

        FsStoreProductScrm product = fsStoreProductService.selectFsStoreProductByProductId(productId);
        List<FsStoreProductAttrScrm> attrs=attrService.selectFsStoreProductAttrByProductId(productId);
        return R.ok().put("data",product).put("attrs", attrs);
    }


    @GetMapping("/getAllStoreProductRule")
    public R getAllList()
    {

        List<FsStoreProductRuleScrm> list = fsStoreProductService.selectFsStoreProductRuleList();
        return R.ok().put("data",list);
    }



    @Log(title = "商品管理", businessType = BusinessType.INSERT, businessTypeExpression = "#p0.getProductId()>0? T(com.fs.common.enums.BusinessType).UPDATE: T(com.fs.common.enums.BusinessType).INSERT"
            , isStoreLog = true, logParamExpression = "#p0.getProductId()>0? new String[]{'商品','修改商品'}: new String[]{'商品','新增商品'}")
    @PostMapping(value = "/addOrEdit")
    public R addOrEdit(@RequestBody FsStoreProductAddEditParam fsStoreProduct)
    {
        fsStoreProduct.setStoreId(UserUtil.getLoginUserStoreID());

        return fsStoreProductService.addOrEdit(fsStoreProduct);
    }

    /**
     * 商品审核日志
     * */
    @GetMapping("/auditLog")
    public R auditLog(@RequestParam("productId") String productId){
        return R.ok().put("auditLog",storeAuditLogUtil.selectOperLogByMainId(Long.valueOf(productId),"商品"));
    }

    /**
     * 商品复制
     * @param product 商品对象
     * @return R
     * */
    @PostMapping("/copyProduct")
    @Log(title = "复制商品", businessType = BusinessType.INSERT, isStoreLog = true, logParam = {"商品", "复制商品"})
    public R copyProduct(@RequestBody FsStoreProductScrm product) {
        return fsStoreProductService.copyProduct(product);
    }

}
