/*******************************************************************************
 * Copyright(c) 2022 dongke All rights reserved. / Confidential
 * 类的信息：
 *		1.程序名称：
 * 编辑履历：
 *		作者				日期					版本				修改内容
 *		于继渤		 2024-1-23			1.00		    商品属性
 *******************************************************************************/
const Constants = require('@/utils/Constants.js');
const util = require('@/utils/util.js')
const mixins = require('@/mixins/index.js')
import Dialog from '@/dist/dialog/dialog.js';
const app = getApp()
Page({
  mixins: [mixins],
  /**
   * 页面的初始数据
   */
  data: {
    routeObjNameGoTo: 'goodsBrand',
    goodsBrandService: app.globalData['goodsBrandService'],
    goodsCategoryService: app.globalData['goodsCategoryService'],
    goodsSeriesService: app.globalData['goodsSeriesService'],
    unitService: app.globalData['unitService'],
    commonService: app.globalData['commonService'],
    // 路由
    routeObjName: 'productAttribute',
    dataItem: null,
    // 查询条件
    searchContent: [{
      code: 'flgValid', key: 'valueList', title: mixins.$t('allValidInvalid'), searchType: Constants.searchType.switch,

      list: [
        { code: 1, title: mixins.$t('valid'), value: true, checked: true },
        { code: 2, title: mixins.$t('invalid'), value: false }]
    }],
    // 列表区（内容）商品品牌
    contentList: [
      { name: 'brandCode', title: mixins.$t('brandCode') },
      { name: 'brandName', title: mixins.$t('brandName') },
      { name: 'supplierNames', title: mixins.$t('supplier') }
    ],
    buttonSaveList: [{ code: 'add', title: '新建', width: '120rpx', color: '#CAA977' }],
    contentSaveList: [],
    formDataName: mixins.$t('goodsBrand'),
    popContent:
      [
        { code: 'brandCode', type: 'str', title: mixins.$t('brandCode'), required: false, readonly: true, },
        { code: 'brandName', type: 'str', title: mixins.$t('brandName'), required: true },
        {
          code: 'supplierIds', formMode: 'index', idKey: 'roleId', chooseType: true, name: 'supplierNames',
          title: mixins.$t('supplier'), type: 'choose', required: true, dropType: 'supplier', required: true,
        },
        { code: 'remarks', type: 'str', title: mixins.$t('remarks'), required: false }
      ],
    sideKey: 0,
    pageFlag: false,
  },

  /**
     * @desc   : 侧滑事件
     * @author : 于继渤
     * @date   : 2024/1/26 11:46
     */
  changeSwipe(e) {
    let item = e.detail.item
    //停用启用
    let param = {
      brandId: item.brandId,
      flgValid: !item.flgValid,
    }
    this.setData({
      formData: JSON.stringify(param)
    })
    //执行编辑操作
    this.save({})
  },

  /**
     * @desc :   启用停用
     * @date : 2024/2/1 15:49
     * @author : 于继渤
     */
  deactivateEnable(e) {
    let item = e.detail.item
    let service = null
    let id = null

    console.log('item', item)
    if (this.data.formDataName == mixins.$t('goodsBrand')) {
      service = this.data.goodsBrandService
      id = 'brandId'

      let that = this
      if (item.supplierIds) {

        //提示信息
        Dialog.confirm({
          message: '已经有供应商引用了品牌，不允许停用，是否跳转到供应商页面?',
        }).then(() => {
          //跳转
          wx.navigateTo({
            url: '/package-purchase/pages/supplier-list/supplier-list',
            success: function (res) {
              res.eventChannel.emit('params', { formMode: Constants.formMode.index })
            }
          })
        }).catch(() => {
        })
        return
      }

    }
    if (this.data.formDataName == mixins.$t('goodsCategory')) {
      service = this.data.goodsCategoryService
      id = 'catId'
    }
    if (this.data.formDataName == mixins.$t('goodsSeries')) {
      service = this.data.goodsSeriesService
      id = 'seriesId'
    }
    if (this.data.formDataName == mixins.$t('unit')) {
      service = this.data.unitService
      id = 'unitId'
    }
    //执行接口
    this.handleMoreDataIsValid(service, item, id)
  },

  /**
   * @desc   : 新建编辑事件
   * @author : 于继渤
   * @date   : 2024/1/26 11:46
   */
  editItems(e) {
    let data = e.detail.form
    this.setData({
      formData: JSON.stringify(data)
    })
    //执行保存编辑操作
    this.save({})
  },

  /**
   * @desc   : 商品种类停用启用
   * @author : 于继渤
   * @date   : 2024/1/26 11:46
   */
  onSwipeBind(e) {
    let swipeFlag = true
    let item = e.detail.currentTarget.dataset.item
    console.log(e)
    // return
    let flgValidList = []
    if (item && item.children && item.children.length > 0) {
      flgValidList = item.children.filter(res => {
        return res.flgValid == true
      })
    }
    console.log('flgValidList',flgValidList,item.children)
    if( !item.children || (flgValidList.length == (item.children && item.children.length)) || flgValidList.length == 0) {
      this.handleMoreDataIsValid(this.data.goodsCategoryService, item, 'catId')
      
    } else {
      Dialog.confirm({
        message: '有启用下级种类，不能停用',
      }).then(() => {
      }).catch(() => {
      })
      return
    }

  },



  /**
   * @desc : 保存编辑
   * @author : 于继渤
   * @date : 2022/5/26 20:16
   */
  saveData(params) {
    let id = null
    let service = null
    if (this.data.formDataName == mixins.$t('goodsBrand')) { //商品品牌
      service = this.data.goodsBrandService
      id = params.brandId
    } else if (this.data.formDataName == mixins.$t('goodsCategory')) { //商品种类
      service = this.data.goodsCategoryService
      id = params.catId
    } else if (this.data.formDataName == mixins.$t('goodsSeries')) { //商品系列
      service = this.data.goodsSeriesService
      id = params.seriesId
    } else if (this.data.formDataName == mixins.$t('unit')) { //计量单位
      service = this.data.unitService
      id = params.unitId
    }
    if (id) { //编辑
      return this.excute(service, service.update, params);
    } else { //新建
      return this.excute(service, service.insert, params);
    }

  },
  /**
    * @desc   : 处理数据
    * @author : 于继渤
    * @date   : 2024/1/26 11:46
    */
  handleData(data) {
    this.searchData()
  },
  /**
   * @desc : 分类切换
   * @author : 于继渤
   * @date : 2022/5/26 20:16
   */
  changeSidebar(e) {
    let detail = e.detail
    this.setData({
      formDataName: this.data.sidebarList[detail].kindName
    })
    this.searchData()
  },

  /**
   * @desc : 列表对象点击
   * @author : 于继渤
   * @date : 2024/1/23 9:16
   */
  toDetail(e) {
    this.setPopContent();
    console.log(e)
    let item = e.detail.item
    this.setData({
      popContent: this.data.popContent,
      showPop: true,
      dataItem: JSON.stringify(item)
    })
  },

  /**
   * @desc : 新建
   * @author : 于继渤
   * @date : 2024/1/23 9:16
   */
  toAdd() {
    this.setPopContent();
    this.setData({
      dataItem: null,
      formData: null,
      showPop: true,
    })
    //清除组件数据
    this.selectComponent('#popup').setFormNull()
  },

  /**
    * @desc :   处理接口返回数据
    * @date : 2024/2/1 15:49
    * @author : 于继渤
    */
  handleSearchData(tableData) {
    if (this.data.formDataName == mixins.$t('goodsCategory')) {
      tableData.forEach(element => {
        element.open = true
      });
      this.setData({
        tableData: util.convertToChildren(tableData, 'parentId', 'catId', null)
      })
 

      
      const myComponent = this.selectComponent('#treeSelect');
      myComponent.setDataFromPage(this.data.tableData);
    }

  },


  /**
   * @desc : 设置查询参数
   * @author : 于继渤
   * @date : 2024/1/23 9:16
   */
  setSearchParams(params) {
    //有效标识
    params.flgValidList = params.flgValidList ? params.flgValidList : [true]
    if (this.data.formDataName == mixins.$t('goodsCategory')) {
      params.pageSize = 100000
      params.currentPage = 1
    }
    return params
  },

  /**
   * @desc : 加载数据
   * @author : 于继渤
   * @date : 2024/1/23 9:16
   */
  getData(params) {
    if (this.data.formDataName == mixins.$t('goodsBrand')) { //商品品牌
      return this.excute(this.data.goodsBrandService, this.data.goodsBrandService.selectByCond, params);
    } else if (this.data.formDataName == mixins.$t('goodsCategory')) { //商品种类
      return this.excute(this.data.goodsCategoryService, this.data.goodsCategoryService.selectByCond, params);
    } else if (this.data.formDataName == mixins.$t('goodsSeries')) { //商品系列
      return this.excute(this.data.goodsSeriesService, this.data.goodsSeriesService.selectByCond, params);
    } else if (this.data.formDataName == mixins.$t('unit')) { //计量单位
      return this.excute(this.data.unitService, this.data.unitService.selectByCond, params);
    }

  },

  /**
   * @desc :   获取左侧数据
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  getDataKind() {
    return this.excute(this.data.commonService, this.data.commonService.getDataKind, {
      kindType: Constants.kindType.goodsAttr
    }).then(res => {
      this.setData({
        sidebarList: res.data.data
      })
    })
  },
  /**
   * @desc : 设置pop字段
   * @author : 于继渤
   * @date : 2024/1/23 9:16
   */
  setPopContent() {
    let formDataName = this.data.formDataName
    let popContent = this.data.popContent
    let routeObjNameGoTo = this.data.routeObjNameGoTo
    if (formDataName == mixins.$t('goodsBrand')) {//商品品牌
      popContent =
        [
          { code: 'brandCode', type: 'str', title: mixins.$t('brandCode'), required: false, readonly: true, },
          { code: 'brandName', type: 'str', title: mixins.$t('brandName'), required: true },
          { code: 'supplierIds', name: 'supplierNames', title: 'supplier', type: 'choose', required: true, dropType: 'supplier', required: true, urlKey: 'selectProductAttributeSuppliers', code: 'supplierIds', formMode: 'index', idKey: 'roleId', title: mixins.$t('supplier') },

          { code: 'remarks', type: 'str', title: mixins.$t('remarks'), required: false }
        ]
      routeObjNameGoTo = 'goodsBrand'
    }
    if (formDataName == mixins.$t('goodsCategory')) { //商品种类
      popContent =
        [
          { code: 'catCode', type: 'str', title: mixins.$t('catCode'), required: false, readonly: true, },
          { code: 'parentId', name: 'parentName', title: mixins.$t('parent'), type: 'choose', required: true, required: true, urlKey: 'selectProductTypes', },
          { code: 'catName', type: 'str', title: mixins.$t('catName'), required: true },
          { code: 'remarks', type: 'str', title: mixins.$t('remarks'), required: false }
        ]
      routeObjNameGoTo = 'goodsCategory'
    }
    if (formDataName == mixins.$t('goodsSeries')) { //商品系列
      popContent =
        [
          { code: 'seriesCode', type: 'str', title: mixins.$t('seriesCode'), required: false, readonly: true, },
          { code: 'seriesName', type: 'str', title: mixins.$t('seriesName'), required: true },
          { code: 'remarks', type: 'str', title: mixins.$t('remarks'), required: false }
        ]
    }
    if (formDataName == mixins.$t('unit')) { //计量单位
      popContent =
        [
          { code: 'unitCode', type: 'str', title: mixins.$t('unitCode'), required: false, readonly: true, },
          { code: 'unitName', type: 'str', title: mixins.$t('unitName'), required: true },
          { code: 'decimalPlaces', type: 'number', sign: "", digits: 0, title: mixins.$t('decimalPlaces'), required: true },
          { code: 'remarks', type: 'str', title: mixins.$t('remarks'), required: false }
        ]
    }
    this.setData({
      popContent: popContent,
      routeObjNameGoTo: routeObjNameGoTo
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getDataKind()
    let _this = this;
    wx.getSystemInfo({
      success: function (res) {
        _this.setData({
          windowHeight: res.windowHeight,
          windowWidth: res.windowWidth
        })
      }
    })





  },


})