const app = getApp();
const api = require('@/utils/api.js');
const Constants = require('@/utils/Constants.js')
const mixins = require('@/mixins/index.js')
Page({
  mixins: [mixins],
  /**
   * 页面的初始数据
   */
  data: {
    // 选择数据
    choosedData: [],
    // // 是否显示tab
    // tabFlag: false,
    // 页签默认在第一个
    active: 0,
    // 查询条件
    searchContent: null,
    // 路由
    routeObjName: 'common',
    // 列表区（内容）
    contentList: null,
    // 方法名
    method: null,
    // 字典类型
    dictCode: null,
    // 标题
    title: null,
    // 需要调到的新建路由
    addUrl: null,
    // 是否多选
    chooseFlag: false,
    // 提示信息
    placeholder: [],
    // tab页签
    tagList: [],
    // 用于多选
    valueKey: null,
    labelKey: null,
    // 多选时是否允许重复
    repeatFlag: false,
    // 确定按钮
    buttonList: [{
      name: 'confirm',
      title: '确定'
    }],
  },
  /**
   * @desc : 调到新建
   * @author : 姜永辉
   * @date : 2022/5/23 15:16
   */
  toAdd() {
    if (!this.data.addUrl) {
      return;
    }
    let _this = this
    wx.navigateTo({
      url: this.data.addUrl,
      events: {
        // // 回调后，在这里给页面赋值
        // bandData: function (e) {

        // }
      },
      success: function (res) {
        // 通过eventChannel向被打开页面传送数据 TODO 测试例子url是写死的，实际中，需要从route中读取
        res.eventChannel.emit('params', {})
      }
    })
  },
  /**
   * @desc : 选择数据
   * @author : 周兴
   * @date : 2024/3/25 15:16
   */
  chooseData(e) {
    let list = e.detail.list;
    let item = e.detail.item;
    let valueKey = this.data.valueKey;
    if (!valueKey) {
      this.setData({
        choosedData: list
      })
    } else {
      let choosedData = this.data.choosedData
      // 不允许重复
      if (!this.data.repeatFlag) {
        if (e.detail.checked) { // 勾选
          let filters = choosedData.filter(it => it[valueKey] == item[valueKey])
          if (!filters || filters.length == 0) {
            choosedData.push(item);
          }
        } else { // 取消勾选
          choosedData = choosedData.filter(it => it[valueKey] != item[valueKey])
        }
      } else {
        if (e.detail.checked) { // 勾选
          // 可以重复
          choosedData.push(item);
        }
      }
      this.setData({
        choosedData: choosedData
      })
    }
  },
  /**
   * @desc : 确定事件-返回数据
   * @author : 周兴
   * @date : 2024/3/25 15:16
   */
  confirm() {
    let list = [...this.data.choosedData]
    let id = list.map(it => it[this.data.valueKey])
    let name = list.map(it => it[this.data.labelKey])
    const eventChannel = this.getOpenerEventChannel();
    eventChannel.emit('bindData', {
      data: {
        list,
        id,
        name
      }
    })
    wx.navigateBack({
      delta: 1
    })
  },
  /**
   * @desc : 点击事件-返回数据
   * @author : 姜永辉
   * @date : 2022/5/23 15:16
   */
  toDetail(e) {
    // 如果选择框开启就走确定模式
    if (this.data.chooseFlag) {
      return;
    }
    let item = e.detail.item
    // 读取传入的单据类型
    let route = this.data.chooseRoute
    let data = {}
    switch (route.type) {
      // 部门
      case Constants.chooseType.org:
        data = {
          id: item.orgId,
          name: item.orgName
        }
        break;
      // 员工
      case Constants.chooseType.staff:
        data = {
          id: item.staffId,
          name: item.staffName,
          orgId: item.orgId,
          orgName: item.orgName,
          staffPhone: item.staffPhone,
        }
        break;
         // 角色
      case Constants.chooseType.role:
        data = {
          id: item.roleId,
          name: item.roleName, 
        }
        break;

      //渠道
      case Constants.chooseType.saleChannel:
        data = {
          id: item.channelId,
          name: item.channelName,
          code: item.channelCode
        }
        break;
      //客户来源
      case Constants.chooseType.cusFrom:
        data = {
          id: item.dataId,
          name: item.dataValue,
          code: item.dataCode
        }
        break;
      // 供应商
      case Constants.chooseType.supplier:
        data = {
          id: item.supId,
          name: item.supName,
          item: item
        }
        break;
      // 对象类型
      case Constants.chooseType.objectType:
        data = {
          id: item.objId,
          name: item.objName,
          objType: item.objType
        }
        break;

      // 仓库
      case Constants.chooseType.warehouse:
        data = {
          id: item.whId,
          name: item.whName
        }
        break;
      case Constants.chooseType.inventorySku:
        data = {
          id: item.whId,
          name: item.whName,
          item: item
        }
        break;
      // 品牌
      case Constants.chooseType.brand:
        data = {
          id: item.brandId,
          name: item.brandName
        }
        break;
      // 系统数据
      case Constants.chooseType.kindData:
        data = {
          id: item.kindCode,
          name: item.kindName
        }
        break;
      // 数据字典
      case Constants.chooseType.dictionary:
        data = {
          id: item.dataId,
          name: item.dataValue,
          dictCode: item.dictCode,
          dataCode: item.dataCode,
          flgDefault: item.flgDefault,
        }
        break;
      // 系统数据
      case Constants.chooseType.kindType:
        data = {
          id: item.id,
          name: item.kindName,
          kindType: item.kindType,
          kindCode: item.kindCode,
          flgDefault: item.flgDefault,
        }
        break;
      default:
        data = {}
        break;
    }
    const eventChannel = this.getOpenerEventChannel();
    eventChannel.emit('bindData', {
      data: data
    })
    wx.navigateBack({
      delta: 1
    })
  },
  /**
   * @desc :   设置查询参数
   * @date : 2024/3/25 15:49
   * @author : 周兴
   */
  setSearchParams(params) {
    // 字典类别
    if (this.data.dictCode) {
      params.dictCode = this.data.dictCode
    }
    // 系统数据
    if (this.data.kindType) {
      params.kindType = this.data.kindType
    }
    console.log('eee',this.data.chooseRoute);
    let chooseType = this.data.chooseRoute.type;
    // 供应商
    if (chooseType == Constants.chooseType.supplier) {
      params.supType = "";
      let active = this.data.active
      if (active == 1) { //采购供应商
        params.supType = Constants.kindCode.supplierPur;
      } else if (active == 2) { //服务供应商
        params.supType = Constants.kindCode.supplierService;
      }
    }
    //跟据非标号公司skuid判断库存
    if (chooseType == Constants.chooseType.inventorySku) {
      console.log('globalData', app.globalData)

      params.skuId = this.data.item.skuId
      params.nonStdCode = this.data.item.nonStdCode
      params.cpId = app.globalData.company.cpId
    }
    if (chooseType == Constants.chooseType.saleChannel) {
      params.dataSourceCode = Constants.chooseType.saleChannel
    }
    if (chooseType == Constants.chooseType.cusFrom) {
      params.dataSourceCode = Constants.chooseType.cusFrom
    }

    return params
  },
  /** 
   * @desc : 删除已选
   * @date : 2024年3月26日
   * @author : 周兴
   */
  delChoosed(e) {
    let choosedData = this.data.choosedData;
    choosedData = choosedData.filter((it, index) => index != e.detail.index)
    this.setData({
      choosedData: choosedData
    })
  },
  /** 
   * @desc : 查询数据
   * @date : 2024年3月23日
   * @author : 周兴
   */
  getData(params) {
    console.log('this.data.routeObjName', this.data.method)
    let service = app.globalData[this.data.routeObjName + 'Service'];
    return this.excute(service, service[this.data.method], params);
  },
  /**
   * @desc : tab切换（列表和已选）
   * @date : 2024/3/25 15:49
   * @author : 周兴
   */
  changeTag(e) {
    this.setData({
      active: e.detail.index
    })
  },
  /**
   * @desc : 切换tab
   * @date : 2024/2/1 15:49
   * @author : 周兴
   */
  onChangeTabs(e) {
    let index = e.detail.detail.index
    this.setData({
      active: index,
    })
    // 查询
    this.searchData()
  },
  /** 
   * @desc : 生命周期函数（初始加载）
   * @date : 2024年3月23日
   * @author : 周兴
   */
  loadInit(e) {
    let route = this.data.chooseRoute;
    if (!route || !route.type) {
      return;
    }
    let title;

    // 读取传入的单据类型
    let chooseType = route.type
    switch (chooseType) {
      // 角色
      case Constants.chooseType.role:
        title = "角色"
        this.setData({
          addUrl: '/package-basic-data/pages/role/add/add',
          routeObjName: 'common',
          method: 'getRole',
          title: 'roleName',
          chooseFlag: route.chooseFlag,
          contentList: [{
            name: 'roleCode',
            title: '编码'
          },],
          placeholder: ['roleName']
        })
        break;
      // 部门
      case Constants.chooseType.org:
        title = "部门"
        this.setData({
          addUrl: '/package-basic-data/pages/org/org',
          routeObjName: 'common',
          method: 'getOrg',
          title: 'orgName',
          contentList: [{
            name: 'orgCode',
            title: '部门编码'
          },],
          placeholder: ['orgName']
        })
        break;
      // 员工
      case Constants.chooseType.staff:
        title = "员工"
        this.setData({
          addUrl: '/package-basic-data/pages/staff/add/add',
          routeObjName: 'common',
          method: 'getStaff',
          title: 'staffName',
          contentList: [{
            name: 'staffCode',
            title: '员工编码'
          },
          {
            name: 'orgName',
            title: '部门'
          },
          ],
          placeholder: ['staffName']
        })
        break;
      //销售渠道
      case Constants.chooseType.saleChannel:
        title = "销售渠道"
        this.setData({
          routeObjName: 'common',
          method: 'getInitData',
          title: 'channelName',
          placeholder: ['channelName']
        })
        break;

      //客户来源
      case Constants.chooseType.cusFrom:
        title = "客户来源"
        this.setData({

          routeObjName: 'common',
          method: 'getInitData',
          title: 'dataValue',
          contentList: [{
            name: 'dataCode',
            title: '来源编码'
          },
          {
            name: 'dataValue',
            title: '来源名称'
          },
          ],
          placeholder: ['cusFromName']
        })
        break;
      //销售渠道
      case Constants.chooseType.saleChannel:
        title = "销售渠道"
        this.setData({
          routeObjName: 'common',
          method: 'getInitData',
          title: 'channelName',
          placeholder: ['channelName']
        })
        break;
      // 供应商
      case Constants.chooseType.supplier:
        title = "供应商"
        this.setData({
          addUrl: '/package-purchase/pages/supplier-list/add/add',
          routeObjName: 'supplier',
          method: 'selectByCond',
          title: 'supName',
          valueKey: 'supId',
          labelKey: 'supName',
          chooseFlag: route.chooseFlag,
          contentList: [{
            name: 'supTypeName',
            title: '供应商类别'
          },
          {
            name: 'returnAddress',
            title: '供应商地址'
          },
          {
            name: 'payableResidue',
            title: '剩余应付'
          },
          {
            name: 'paymentResidue',
            title: '预付金额'
          },
          ],
          placeholder: ['supplier']
        })
        // 多选时就不要有其他的tag标签
        if (!route.chooseFlag) {
          this.setData({
            tagList: [{
              title: mixins.$t("all") //全部
            }, {
              title: mixins.$t("procurementSupplier") //采购供应商
            }, {
              title: mixins.$t("serviceProvider") // 服务供应商
            }],
          })
        }
        break;
      // 仓库
      case Constants.chooseType.warehouse:
        title = "仓库"
        this.setData({
          addUrl: '/package-basic-data/pages/basic-data/basic-data',
          routeObjName: 'common',
          method: 'warehouseListBy',
          title: 'whName',
          contentList: [{
            name: 'supervisor',
            title: '仓库主管'
          },
          {
            name: 'contactPhone',
            title: '联系电话'
          },
          ],
          placeholder: ['whName']
        })
        break;
      case Constants.chooseType.inventorySku:
        title = "库存"
        this.setData({
          routeObjName: 'common',
          method: 'getInventory',
          title: 'staffName',
          contentList: [
            {
              name: 'whName',
              title: '仓库名称'
            }, {
              name: 'skuName',
              title: '商品名称'
            },
            {
              name: 'skuCode',
              title: '商品编码'
            },
            {
              name: 'usableQty',
              title: '可售量'
            },
            {
              name: 'invQty',
              title: '库存量'
            },

          ],
          placeholder: ['whName']
        })
        break;
      // 品牌
      case Constants.chooseType.brand:
        title = "品牌"
        this.setData({
          addUrl: '/package-basic-data/pages/basic-data/basic-data',
          routeObjName: 'common',
          method: 'goodsBrandListBy',
          chooseFlag: route.chooseFlag,
          repeatFlag: route.repeatFlag,
          title: 'brandName',
          contentList: [{
            name: 'brandCode',
            title: '品牌编码'
          },
          {
            name: 'brandName',
            title: '品牌名称'
          },
          ],
          placeholder: ['brandName']
        })
        break;
      // 数据字典
      case Constants.chooseType.dictionary:
        title = "数据字典"
        this.setData({
          addUrl: '/package-basic-data/pages/basic-data/basic-data',
          routeObjName: 'common',
          method: 'getDictionaryData',
          dictCode: route.dictCode,
          chooseFlag: route.chooseFlag,
          repeatFlag: route.repeatFlag,
          valueKey: 'dataId',
          title: 'dataValue',
          contentList: [{
            name: 'dataCode',
            title: '数据编码'
          },
          {
            name: 'dictCode',
            title: '字典项目'
          },
          ],
          placeholder: ['orgName']
        })
        break;
      // 系统数据
      case Constants.chooseType.kindData:
        title = "系统数据"
        this.setData({
          routeObjName: 'common',
          method: 'getDataKind',
          kindType: route.kindType,
          valueKey: 'kindCode',
          title: 'kindName',
          chooseFlag: route.chooseFlag,
          repeatFlag: route.repeatFlag,
          contentList: [{
            name: 'kindCode',
            title: '数据代码'
          },
          {
            name: 'kindName',
            title: '数据名称'
          },
          ],
          placeholder: ['sensitiveName']
        })
        break;
      // 对象类型
      case Constants.chooseType.objectType:
        title = "对象类型"
        this.setData({
          routeObjName: 'common',
          method: 'getSupplierAndCustomerData',
          title: 'objName',
          contentList: [{
            name: 'objCode',
            title: '对象编码'
          },
          {
            name: 'objTypeName',
            title: '对象'
          },
          {
            name: 'addressFull',
            title: '地址'
          },
          ],
          searchContent: [{
            code: 'supplier-customer',
            title: '选择对象',
            searchType: Constants.searchType.switch,
            list: [{
              code: 'supplier',
              title: '供应商',
              value: 1,
            },
            {
              code: 'customer',
              title: '客户',
              value: 2
            }
            ]
          },

          ],
          placeholder: ['customerName', 'supplierName', 'address', 'telephone']
        })

        break;

      default:
        break;
    }
    // 多选，数据回显到已选列表
    if (this.data.chooseFlag && this.data.item && this.data.item.data) {
      this.setData({
        choosedData: this.data.item.data
      })
    }
    wx.setNavigationBarTitle({
      title: '选择' + title,
    })
    // 调取查询
    this.searchData();
  },
})