/*******************************************************************************
 * 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')
import Dialog from '@/dist/dialog/dialog.js';
const mixins = require('@/mixins/index.js')
const app = getApp()
Page({
  mixins: [mixins],
  /**
   * 页面的初始数据
   */
  data: {
    gradeCode: app.globalData.company.gradeCode,
    flgValidList: null,
    flgDefault: 'flgDefault',
    navigateBackFlag: true,
    routeObjNameGoTo: '',
    formDataName: '仓库',
    dictCode: mixins.$t('warehouseSys'),
    //接口
    warehouseService: app.globalData['warehouseService'],
    saleChannelService: app.globalData['saleChannelService'],
    commonService: app.globalData['commonService'],
    routeObjName: 'basicData',
    tableData: [],
    buttonSaveList: [{ code: 'sort', title: '排序', width: '120rpx', plain: true }, { code: 'add', title: '新建', width: '120rpx', }],
    contentSaveList: [],
    // 查询条件
    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 }]
    }],
    sidebarList: [],
    contentList: [
      { name: 'whCode', title: mixins.$t('whCode') },
      { name: 'whName', title: mixins.$t('whName') },
      { name: 'supervisor', title: mixins.$t('supervisor') }
    ],
    contentObj: {
      //TODO 怎么国际化 ?
      // '基础资料-仓库': [{ name: 'whCode', title: mixins.$t('whCode') },
      // { name: 'supervisor', title: mixins.$t('supervisor') }],
      // '基础资料-渠道': [{ name: 'channelCode', title: mixins.$t('channelCode') },
      // ],
      // '基础资料-收入': [{ name: 'dataCode', title: mixins.$t('incomeCode') },
      // ],
      // '基础资料-支出': [{ name: 'dataCode', title: mixins.$t('expenditureCode') },
      // ],
      // '基础资料-入库': [{ name: 'dataCode', title: mixins.$t('reasonCode') },
      // ],
      // '基础资料-出库': [{ name: 'dataCode', title: mixins.$t('reasonCode') },
      // ],
      // '基础资料-账户': [{ name: 'dataCode', title: mixins.$t('accountCode') },
      // ],
      // '基础资料-来源': [{ name: 'dataCode', title: mixins.$t('sourceCode') },
      // ],
      // '基础资料-盈亏原因': [{ name: 'dataCode', title: mixins.$t('profitLossCode') },
      // ],
    },
    popContent:
      [
        { code: 'whCode', type: 'str', title: mixins.$t('whCode'), required: false, readonly: true, },
        { code: 'whName', type: 'str', title: mixins.$t('whName'), required: true },
        {
          name: 'supervisor',
          code: 'supervisor',
          title: mixins.$t("supervisor"),
          type: 'choose',
          required: true,
          urlKey: 'chooseStaff'
        },
        { code: 'contactPhone', type: 'str', title: mixins.$t('contactPhone'), required: true },
        { code: 'remarks', type: 'str', title: mixins.$t('remarks'), required: false }
      ],
    sideKey: 0,
  },

  /**
   * @desc : 设置pop字段
   * @author : 于继渤
   * @date : 2024/1/23 9:16
   */
  setPopContent(item) {
    let formDataName = this.data.formDataName
    let dictCode = this.data.dictCode

    let popContent = this.data.popContent
    let contentList = this.data.contentList
    let dataItemData = {}
    let dataItem = item
    let routeObjNameGoTo = this.data.routeObjNameGoTo
    this.setData({
      flgDefault: 'flgDefault'
    })
    if (dictCode == mixins.$t('warehouseSys')) {//仓库档案
      //设置新建编辑字段
      console.log('dictCode', dictCode)
      if (dataItem) {
        popContent =
          [
            { code: 'whCode', type: 'str', title: mixins.$t('whCode'), required: false, readonly: true, },
            { code: 'whName', type: 'str', title: mixins.$t('whName'), required: true },
            {
              name: 'supervisor',
              code: 'supervisor',
              title: mixins.$t("supervisor"),
              type: 'choose',
              required: true,
              urlKey: 'chooseStaff'
            },
            { code: 'contactPhone', type: 'str', title: mixins.$t('contactPhone'), required: true },
            { code: 'remarks', type: 'str', title: mixins.$t('remarks'), required: false }
          ]
      } else {
        //新建
        popContent =
          [
            // { code: 'whCode', type: 'str', title: mixins.$t('whCode'), required: false, readonly: true, },
            { code: 'whName', type: 'str', title: mixins.$t('whName'), required: true },
            {
              name: 'supervisor',
              code: 'supervisor',
              title: mixins.$t("supervisor"),
              type: 'choose',
              required: true,
              urlKey: 'chooseStaff'
            },
            { code: 'contactPhone', type: 'str', title: mixins.$t('contactPhone'), required: true },
            { code: 'remarks', type: 'str', title: mixins.$t('remarks'), required: false }
          ]

      }

      routeObjNameGoTo = 'warehouse'
      console.log('popContent', popContent)
    } else if (dictCode == mixins.$t('saleChannelSys')) {
      //设置新建编辑字段
      if (dataItem) {
        popContent =
          [
            { code: 'channelCode', type: 'str', title: mixins.$t('channelCode'), required: false, readonly: true, },
            { code: 'channelName', type: 'str', title: mixins.$t('channelName'), required: true },
            { code: 'remarks', type: 'str', title: mixins.$t('remarks'), required: false }
          ]
      } else {
        popContent =
          [
            // { code: 'channelCode', type: 'str', title: mixins.$t('channelCode'), required: false, readonly: true, },
            { code: 'channelName', type: 'str', title: mixins.$t('channelName'), required: true },
            { code: 'remarks', type: 'str', title: mixins.$t('remarks'), required: false }
          ]
      }


    } else {
      if (dictCode == mixins.$t('incomeCategorySys')) {
        //设置新建编辑字段 收入类别
        if (dataItem) {
          popContent =
            [
              { code: 'dataCode', type: 'str', title: mixins.$t('incomeCode'), required: false, readonly: true, },
              { code: 'dataValue', type: 'str', title: mixins.$t('incomeName'), required: true }
            ]
        } else {
          popContent =
            [
              // { code: 'dataCode', type: 'str', title: mixins.$t('incomeCode'), required: false, readonly: true, },
              { code: 'dataValue', type: 'str', title: mixins.$t('incomeName'), required: true }
            ]
        }

        this.setData({
          flgDefault: null
        })
      }
      if (dictCode == mixins.$t('expenditureCategorySys')) {
        //设置新建编辑字段 支出类别
        if (dataItem) {
          popContent =
            [
              { code: 'dataCode', type: 'str', title: mixins.$t('expenditureCode'), required: false, readonly: true, },
              { code: 'dataValue', type: 'str', title: mixins.$t('expenditureName'), required: true }
            ]
        } else {
          popContent =
            [
              // { code: 'dataCode', type: 'str', title: mixins.$t('expenditureCode'), required: false, readonly: true, },
              { code: 'dataValue', type: 'str', title: mixins.$t('expenditureName'), required: true }
            ]
        }

        this.setData({
          flgDefault: null
        })
      }
      if (dictCode == mixins.$t('reasonStorageSys')) {
        //设置新建编辑字段 入库原因
        if (dataItem) {
          popContent =
            [
              { code: 'dataCode', type: 'str', title: mixins.$t('reasonCode'), required: false, readonly: true, },
              { code: 'dataValue', type: 'str', title: mixins.$t('reasonName'), required: true }
            ]
        } else {
          popContent =
            [
              // { code: 'dataCode', type: 'str', title: mixins.$t('reasonCode'), required: false, readonly: true, },
              { code: 'dataValue', type: 'str', title: mixins.$t('reasonName'), required: true }
            ]
        }

        this.setData({
          flgDefault: null
        })
      }
      if (dictCode == mixins.$t('reasonOutboundSys')) {
        //设置新建编辑字段 出库原因
        if (dataItem) {
          popContent =
            [
              { code: 'dataCode', type: 'str', title: mixins.$t('reasonCode'), required: false, readonly: true, },
              { code: 'dataValue', type: 'str', title: mixins.$t('reasonName'), required: true }
            ]
        } else {
          popContent =
            [
              // { code: 'dataCode', type: 'str', title: mixins.$t('reasonCode'), required: false, readonly: true, },
              { code: 'dataValue', type: 'str', title: mixins.$t('reasonName'), required: true }
            ]
        }

        this.setData({
          flgDefault: null
        })
      }
      if (dictCode == mixins.$t('accountCategorySys')) {
        //设置新建编辑字段 账户类别
        if (dataItem) {
          popContent =
            [
              { code: 'dataCode', type: 'str', title: mixins.$t('accountCode'), required: false, readonly: true, },
              { code: 'dataValue', type: 'str', title: mixins.$t('accountName'), required: true }
            ]
        } else {
          popContent =
            [
              // { code: 'dataCode', type: 'str', title: mixins.$t('accountCode'), required: false, readonly: true, },
              { code: 'dataValue', type: 'str', title: mixins.$t('accountName'), required: true }
            ]
        }



        this.setData({
          flgDefault: null
        })
      }
      if (dictCode == mixins.$t('customerSourceSys')) {
        //设置新建编辑字段 客户来源
        if (dataItem) {
          popContent =
            [
              { code: 'dataCode', type: 'str', title: mixins.$t('sourceCode'), required: false, readonly: true, },
              { code: 'dataValue', type: 'str', title: mixins.$t('sourceName'), required: true },
            ]
        } else {
          popContent =
            [
              // { code: 'dataCode', type: 'str', title: mixins.$t('sourceCode'), required: false, readonly: true, },
              { code: 'dataValue', type: 'str', title: mixins.$t('sourceName'), required: true },
            ]
        }


      }
      if (dictCode == mixins.$t('profitLossSys')) {
        //设置新建编辑字段 客户来源
        if (dataItem) {
          popContent =
            [
              { code: 'dataCode', type: 'str', title: mixins.$t('profitLossCode'), required: false, readonly: true, },
              { code: 'dataValue', type: 'str', title: mixins.$t('profitLossName'), required: true },
            ]
        } else {
          popContent =
            [
              // { code: 'dataCode', type: 'str', title: mixins.$t('profitLossCode'), required: false, readonly: true, },
              { code: 'dataValue', type: 'str', title: mixins.$t('profitLossName'), required: true },
            ]
        }

        this.setData({
          flgDefault: null
        })
      }
      popContent.push({ code: 'remarks', type: 'str', title: mixins.$t('remarks'), required: false })
    }

    this.setData({
      contentList: contentList,
      popContent: popContent,
      routeObjNameGoTo: routeObjNameGoTo
    })
  },
  /**
 * @desc :   底部按钮
 * @date : 2024/2/1 15:49
 * @author : 于继渤
 */
  open(e) {
    let name = e.detail.name
    if (name == 'sort') {
      this.toSort()
    } else if (name == 'add') {
      this.toAdd()
    }
  },
  /**
   * @desc :   启用停用
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  deactivateEnable(e) {
    let item = e.detail.item
    let service = null
    let id = null
    if (this.data.dictCode == mixins.$t('warehouseSys')) {
      service = this.data.warehouseService
      id = 'whId'
    } else if (this.data.dictCode == mixins.$t('saleChannelSys')) {
      service = this.data.saleChannelService
      id = 'channelId'
    } else { //基础数据
      service = this.data.service
      id = 'dataId'
    }
    if (this.data.dictCode == mixins.$t('accountCategorySys')) { //账户类别
      this.countByCondMoneyAccount(item.dataId, service, item, id)
    } else {

      //执行接口
      this.handleMoreDataIsValid(service, item, id)
    }

  },
  /**
   * @desc :   启用停用账户类别
   * @date : 2024/5/23 15:49
   * @author : 周兴
   */
  countByCondMoneyAccount(dataId, service, item, id) {
    // 标准版需要直接处理，并且处理账户
    if (this.data.gradeCode == Constants.gradeCode.STD) {
      //执行接口
      this.handleMoreDataIsValid(service, item, id)
    } else {
      // 专业版需要判断是否有账户
      this.excute(this.data.service, this.data.service.countByCondMoneyAccount + '/' + dataId, {}).then(res => {
        console.log(res, service)
        if (res.data.code == 200) {
          if (res.data.data > 0 && item.flgValid) {
            //提示信息
            Dialog.confirm({
              message: '账户类别有资金账户不能停用',
            }).then(() => { }).catch(() => {
            });
            return
          } else {
            //执行接口
            this.handleMoreDataIsValid(service, item, id)
          }
        }
      })
    }
  },
  /**
   * @desc : 分类切换
   * @author : 于继渤
   * @date : 2022/5/26 20:16
   */
  changeSidebar(e) {

    let detail = e.detail
    if (!detail) {
      this.setData({
        sideKey: null
      })
    } else {
      this.setData({
        sideKey: e.detail
      })
    }
    this.setData({
      formDataName: this.data.sidebarList[detail].kindName,
      dictCode: this.data.sidebarList[detail].kindCode
    })
    this.setPopContent();
    this.searchData()
  },

  handleData() {
    this.searchData()
  },
  /**
   * @desc : 列表对象点击
   * @author : 于继渤
   * @date : 2024/1/23 9:16
   */
  toDetail(e) {

    let item = e.detail.item
    this.setPopContent(item);
    this.setData({
      popContent: this.data.popContent,
      showPop: true,
      dataItem: JSON.stringify(item),
      historyDataItem: item
    })
  },
  /**
 * @desc : 新建
 * @author : 于继渤
 * @date : 2024/1/23 9:16
 */
  toAdd() {
    this.setPopContent();
    this.setData({
      dataItem: null,
      formData: null,
      showPop: true,
    })
    //清除组件数据
    this.selectComponent('#popup').setFormNull()
    if (this.data.dictCode == mixins.$t('warehouseSys')) {
      let dataItemData = {}
      dataItemData['supervisor'] = app.globalData.user.staffName
      dataItemData['contactPhone'] = app.globalData.user.userPhone
      //设置默认主管
      this.setData({
        dataItem: JSON.stringify(dataItemData)
      })
    }

  },
  /**
  * @desc : 跳转排序
  * @author : 于继渤
  * @date : 2024/1/23 9:16
  */
  toSort() {
    let _this = this
    wx.navigateTo({
      url: this.data.route.sort.url,
      events: {
        // 保存成功后刷新页面
        refresh: function (data) {
          // 刷新一览界面
          _this.searchData();
        }
      },
      success: function (res) {
        // 通过eventChannel向被打开页面传送数据 TODO 测试例子url是写死的，实际中，需要从route中读取
        res.eventChannel.emit('params', {
          formType: _this.data.dictCode,
          formMode: 'index'
        })
      }
    })
  },
  /**
    * @desc : 设置查询参数
    * @author : 于继渤
    * @date : 2024/1/23 9:16
    */
  setSearchParams(params) {
    params.flgValidList = params.flgValidList ? params.flgValidList : [true]
    params.dictCode = this.data.dictCode
    return params
  },



  /**
     * @desc : 加载数据
     * @author : 于继渤
     * @date : 2024/1/23 9:16
     */
  getData(params) {
    if (this.data.dictCode == mixins.$t('warehouseSys')) { //仓库档案
      return this.excute(this.data.warehouseService, this.data.warehouseService.selectByCond, params);
    } else if (this.data.dictCode == mixins.$t('saleChannelSys')) { //销售渠道
      return this.excute(this.data.saleChannelService, this.data.saleChannelService.selectByCond, params);
    } else {
      //基础数据接口
      return this.excute(this.data.service, this.data.service.selectByCond, params);
    }
  },
  /**
    * @desc :   获取左侧数据
    * @date : 2024/2/1 15:49
    * @author : 于继渤
    */
  getDataKind() {
    // 读取系统字典
    let sidebarList = app.globalData.dataKindList.filter(it => it.kindType == Constants.kindType.basicData)
    console.log('gradeCode', this.data.gradeCode);
    if (this.data.gradeCode == Constants.gradeCode.STD) {
      sidebarList = sidebarList.filter(it => (it.kindCode == '基础资料-仓库' || it.kindCode == '基础资料-账户' ||
        it.kindCode == '基础资料-入库' || it.kindCode == '基础资料-渠道'))
    }
    this.setData({
      sidebarList: sidebarList
    })
  },


  /**
    * @desc :   处理接口返回数据
    * @date : 2024/2/1 15:49
    * @author : 于继渤
    */
  handleSearchData(tableData) {
    tableData.forEach(res => {
      res.listItemTitle = this.data.dictCode
      if (this.data.dictCode == mixins.$t('warehouseSys')) { //仓库档案
        res.title = res.whName
        res['flgDefaultDisabled'] = res.flgDefault
      } else if (this.data.dictCode == mixins.$t('saleChannelSys')) { //销售渠道
        res.title = res.channelName
        res['flgDefaultDisabled'] = res.flgDefault
      } else {
        res.title = res.dataValue
      }

    })
    this.setData({
      tableData: tableData
    })

  },

  /**
   * @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 : 2022/5/26 20:16
   */
  saveData(params) {
    let id = null
    let service = null
    let historyDataItem = this.data.historyDataItem
    if (this.data.dictCode == mixins.$t('warehouseSys')) { //仓库档案
      service = this.data.warehouseService
      id = params.whId
      if (id && !historyDataItem.flgDefault && params.flgDefault) {
        //判断默认给提示
        this.isFlgDefault(id, historyDataItem, params, service)
        return
      }

    } else
      if (this.data.dictCode == mixins.$t('saleChannelSys')) { //销售渠道
        service = this.data.saleChannelService
        id = params.channelId
        if (id && !historyDataItem.flgDefault && params.flgDefault) {
          //判断默认给提示
          this.isFlgDefault(id, historyDataItem, params, service)
          return
        }
      } else { //基础数据
        service = this.data.service
        id = params.dataId
        params.dictCode = this.data.dictCode
        if (id && !historyDataItem.flgDefault && params.flgDefault && this.data.dictCode == '基础资料-账户') {
          //判断默认给提示
          this.isFlgDefault(id, historyDataItem, params, service)
          return
        }
      }
    if (id) { //编辑
      if (this.data.dictCode == '基础资料-账户') {
        if (this.data.gradeCode == Constants.gradeCode.STD) { //标准
          params.gradeCode = this.data.gradeCode
          // params.orgId = app.globalData.user.orgId
        }
      }
      return this.excute(service, service.update, params).then(result => {
        if (result && result.data && result.data.code === Constants.SUCESS_CODE) {
          wx.showToast({
            title: '保存成功',
            image: '/static/image/success.png',
            duration: 2000
          })
          // 执行查询方法
          this.searchData()
          // 编辑关闭弹出pop
          this.setData({
            showPop: false
          })
        }
      });
    } else { //新建
      this.isFlgDefaultSave(service).then(it => {
        console.log(it, params)
        if (!it && params.flgDefault) {
          //存在默认
          Dialog.confirm({
            message: mixins.$t('defaultInfo'),
          }).then(() => {
            return this.excute(service, service.insert, params).then(res => {
              if (res.data.code === Constants.SUCESS_CODE) {
                wx.showToast({
                  title: '保存成功',
                  image: '/static/image/success.png',
                  duration: 2000
                })
                // 重新查询
                this.searchData()
                //清除组件数据
                this.selectComponent('#popup').setFormNull()
              }
            })
          }).catch(() => {
            this.setData({
              dataItem: null
            })
            // 不清除组件数据  关闭蒙层
            this.selectComponent('#popup').setLoading(false)
            return
          });
        } else {
          if (this.data.dictCode == '基础资料-账户') {
            if (this.data.gradeCode == Constants.gradeCode.STD) { //标准
              params.gradeCode = this.data.gradeCode
              params.orgId = app.globalData.user.orgId
            }
          }

          return this.excute(service, service.insert, params).then(result => {
            if (result && result.data && result.data.code === Constants.SUCESS_CODE) {
              wx.showToast({
                title: '保存成功',
                image: '/static/image/success.png',
                duration: 2000
              })
              // 执行查询方法
              this.searchData()
              //清除组件数据
              this.selectComponent('#popup').setFormNull()
            }
          });
        }
      })
    }
  },
  /**
   * @desc : 编辑默认设置提示
   * @author : 于继渤
   * @date : 2022/5/26 20:16
   */
  isFlgDefault(id, historyDataItem, params, service) {

    Dialog.confirm({
      message: '已存在默认，是否要新作默认',
    }).then(() => {
      this.excute(service, service.update, params).then(res => {
        console.log(res)
        if (res.data.code === Constants.SUCESS_CODE) {
          wx.showToast({
            title: '保存成功',
            image: '/static/image/success.png',
            duration: 2000
          })
          // 重新查询
          this.searchData()
        }
      })
    }).catch(() => {
      console.log('setFormNull')
      //清除组件数据
      this.setData({
        dataItem: null
      })
      this.selectComponent('#popup').setFormNull()
    });
  },

  /**
   * @desc : 新建默认设置提示
   * @author : 于继渤
   * @date : 2022/5/26 20:16
   */
  isFlgDefaultSave(service) {
    this.setData({
      loading: false
    })
    return new Promise((resolve, reject) => {
      this.excute(service, service.selectByCond, {
        flgDefault: true
      }).then(res => {
        if (res.data.data.list && res.data.data.list.length > 0) {
          resolve(false)
        } else {
          resolve(true)
        }
      })
    })


  },

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


  },


})