/*******************************************************************************
 * 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: {
    flgValidList: null,
    navigateBackFlag: true,
    routeObjNameGoTo: '',
    formDataName: mixins.$t('warehouse'),
    //接口
    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', color: '#CAA977' }],
    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: 'whName', title: mixins.$t('whName') },
      { name: 'supervisor', title: mixins.$t('supervisor') }],
      '销售渠道': [{ name: 'channelCode', title: mixins.$t('channelCode') },
      { name: 'channelName', title: mixins.$t('channelName') }],
      '收入类别': [{ name: 'dataCode', title: mixins.$t('incomeCode') },
      { name: 'dataValue', title: mixins.$t('incomeName') }],
      '支出类别': [{ name: 'dataCode', title: mixins.$t('expenditureCode') },
      { name: 'dataValue', title: mixins.$t('expenditureName') }],
      '入库原因': [{ name: 'dataCode', title: mixins.$t('reasonCode') },
      { name: 'dataValue', title: mixins.$t('reasonName') }],
      '出库原因': [{ name: 'dataCode', title: mixins.$t('reasonCode') },
      { name: 'dataValue', title: mixins.$t('reasonName') }],
      '账户类别': [{ name: 'dataCode', title: mixins.$t('accountCode') },
      { name: 'dataValue', title: mixins.$t('accountName') }],
      '客户来源': [{ name: 'dataCode', title: mixins.$t('sourceCode') },
      { name: 'dataValue', title: mixins.$t('sourceName') }],
    },
    popContent:
      [
        { code: 'whCode', type: 'str', title: mixins.$t('whCode'), required: false, readonly: true, },
        { code: 'whName', type: 'str', title: mixins.$t('whName'), required: true },
        { code: 'supervisor', type: 'str', title: mixins.$t('supervisor'), required: true },
        { 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() {
    let formDataName = this.data.formDataName
    let popContent = this.data.popContent
    let contentList = this.data.contentList
    let routeObjNameGoTo = this.data.routeObjNameGoTo
    if (formDataName == mixins.$t('warehouse')) {//仓库档案
      //设置新建编辑字段
      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'
    } else if (formDataName == mixins.$t('saleChannel')) {
      //设置新建编辑字段
      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 (formDataName == mixins.$t('incomeCategory')) {
        //设置新建编辑字段 收入类别
        popContent =
          [
            { code: 'dataCode', type: 'str', title: mixins.$t('incomeCode'), required: false, readonly: true, },
            { code: 'dataValue', type: 'str', title: mixins.$t('incomeName'), required: true }
          ]
      }
      if (formDataName == mixins.$t('expenditureCategory')) {
        //设置新建编辑字段 支出类别
        popContent =
          [
            { code: 'dataCode', type: 'str', title: mixins.$t('expenditureCode'), required: false, readonly: true, },
            { code: 'dataValue', type: 'str', title: mixins.$t('expenditureName'), required: true }
          ]
      }
      if (formDataName == mixins.$t('reasonStorage')) {
        //设置新建编辑字段 入库原因
        popContent =
          [
            { code: 'dataCode', type: 'str', title: mixins.$t('reasonCode'), required: false, readonly: true, },
            { code: 'dataValue', type: 'str', title: mixins.$t('reasonName'), required: true }
          ]
      }
      if (formDataName == mixins.$t('reasonOutbound')) {
        //设置新建编辑字段 出库原因
        popContent =
          [
            { code: 'dataCode', type: 'str', title: mixins.$t('reasonCode'), required: false, readonly: true, },
            { code: 'dataValue', type: 'str', title: mixins.$t('reasonName'), required: true }
          ]
      }
      if (formDataName == mixins.$t('accountCategory')) {
        //设置新建编辑字段 账户类别
        popContent =
          [
            { code: 'dataCode', type: 'str', title: mixins.$t('accountCode'), required: false, readonly: true, },
            { code: 'dataValue', type: 'str', title: mixins.$t('accountName'), required: true }
          ]
      }
      if (formDataName == mixins.$t('customerSource')) {
        //设置新建编辑字段 客户来源
        popContent =
          [
            { code: 'dataCode', type: 'str', title: mixins.$t('sourceCode'), required: false, readonly: true, },
            { code: 'dataValue', type: 'str', title: mixins.$t('sourceName'), required: true },
          ]
      }
      if (formDataName == '客户标签') {
        //设置新建编辑字段 客户来源
        popContent = []
      }
      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.formDataName == mixins.$t('warehouse')) {
      service = this.data.warehouseService
      id = 'whId'
    } else if (this.data.formDataName == mixins.$t('saleChannel')) {
      service = this.data.saleChannelService
      id = 'channelId'
    } else { //基础数据
      service = this.data.service
      id = 'dataId'
    }
    if (this.data.formDataName == mixins.$t('accountCategory')) { //账户类别
      this.countByCondMoneyAccount(item.dataId, service, item, id)
    } else {

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

  },
  countByCondMoneyAccount(dataId, service, item, id) {

    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
    this.setData({
      formDataName: this.data.sidebarList[detail].kindName,
      dictCode: this.data.sidebarList[detail].kindCode
    })
    this.setPopContent();
    this.searchData()
  },
  /**
   * @desc : 列表对象点击
   * @author : 于继渤
   * @date : 2024/1/23 9:16
   */
  toDetail(e) {
    this.setPopContent();
    let item = e.detail.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()
  },
  /**
  * @desc : 跳转排序
  * @author : 于继渤
  * @date : 2024/1/23 9:16
  */
  toSort() {
    let this_ = this
    wx.navigateTo({
      url: this.data.route.sort.url,
      success: function (res) {
        // 通过eventChannel向被打开页面传送数据 TODO 测试例子url是写死的，实际中，需要从route中读取
        res.eventChannel.emit('params', {
          formType: this_.data.formDataName,
          formMode: 'index'
        })
      }
    })
  },
  /**
    * @desc : 设置查询参数
    * @author : 于继渤
    * @date : 2024/1/23 9:16
    */
  setSearchParams(params) {
    params.flgValidList = params.flgValidList ? params.flgValidList : [true]
    params.dictCode = this.data.dictCode
    params.cpId = 1
    return params
  },



  /**
     * @desc : 加载数据
     * @author : 于继渤
     * @date : 2024/1/23 9:16
     */
  getData(params) {
    if (this.data.formDataName == mixins.$t('warehouse')) { //仓库档案
      return this.excute(this.data.warehouseService, this.data.warehouseService.selectByCond, params);
    } else if (this.data.formDataName == mixins.$t('saleChannel')) { //销售渠道
      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() {
    return this.excute(this.data.commonService, this.data.commonService.getDataKind, {
      kindType: Constants.kindType.basicData
    }).then(res => {
      this.setData({
        sidebarList: res.data.data
      })
    })
  },


  /**
    * @desc :   处理接口返回数据
    * @date : 2024/2/1 15:49
    * @author : 于继渤
    */
  handleSearchData(tableData) {

    tableData.forEach(res => {
      res.listItemTitle = this.data.formDataName
    })
    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({})
  },



  // getWarehouseFlgDefaultCount(){
  //    this.excute(this.data.warehouseService, this.data.warehouseService.getWarehouseFlgDefaultFlag, {}).then(res=>{
  //       console.log()
  //    })
  // },

  /**
   * @desc : 保存编辑
   * @author : 于继渤
   * @date : 2022/5/26 20:16
   */
  saveData(params) {
    let id = null
    let service = null
    let historyDataItem = this.data.historyDataItem
    if (this.data.formDataName == mixins.$t('warehouse')) { //仓库档案
      service = this.data.warehouseService
      id = params.whId
      if (id && !historyDataItem.flgDefault && params.flgDefault) {
        //判断默认给提示
        this.isFlgDefault(id, historyDataItem, params, service)
        return
      }

    } else
      if (this.data.formDataName == mixins.$t('saleChannel')) { //销售渠道
        service = this.data.saleChannelService
        id = params.channelId
      } 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) { //编辑
      return this.excute(service, service.update, params);
    } else { //新建
      return this.excute(service, service.insert, params);
    }

  },
  /**
   * @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(() => {
    });
  },



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


  },


})