/*******************************************************************************
 * Copyright(c) 2022 dongke All rights reserved. / Confidential
 * 类的信息：
 *		1.程序名称：
 * 编辑履历：
 *		作者				日期					版本				修改内容
 *		王英杰		 2024-1-24			1.00		    新建供应商
 *******************************************************************************/
const mixins = require('@/mixins/index.js')
const app = getApp()
const Constants = require('@/utils/Constants')
Page({
  mixins: [mixins],
  /**
   * 页面的初始数据
   */
  data: {
    gradeCode: app.globalData.company.gradeCode,
    buttonList: [{
      name: 'merge',
      title: mixins.$t("save"), //'保存'
    }],
    cardList: ['main', 'staff', 'other'],
    contentObj: {
      main: [{ //供应商名称
        code: 'supName',
        type: 'textarea',
        title: mixins.$t("supplierName"),
        required: true,
      }, { //供应商类别
        code: 'supType',
        name: 'supTypeName',
        title: mixins.$t("supplierType"),
        type: 'drop',
        dropType: 'supType',
        // type: 'choose',
        // urlKey: 'chooseSupplierCategory',
        required: true,
        changeObj: {
          [Constants.kindCode.supplierPur]: {
            hide: ['serviceCategorie'],
            visible: ['brandId']
          },
          [Constants.kindCode.supplierOutsourcing]: {
            hide: ['serviceCategorie'],
            visible: ['brandId']
          },
          [Constants.kindCode.supplierService]: {
            hide: ['brandId'],
            visible: ['serviceCategorie']
          }
        },
      }, { //供应品牌
        code: 'brandId',
        name: 'brandName',
        title: mixins.$t("brandId"),
        type: 'choose',
        urlKey: 'chooseBrandy',
      }, { //服务类别 
        code: 'serviceCategorie',
        name: 'serviceCategoriesName',
        title: mixins.$t("ServiceCategories"),
        type: 'choose',
        urlKey: 'chooseServiceCategory',
      }, { //联系人
        code: 'contactName',
        type: 'textarea',
        title: mixins.$t("contactName"),
      },
      { //联系电话
        code: 'contactPhone',
        type: 'phone',
        title: mixins.$t("contactPhone"),

      }, {
        code: 'returnAddress',
        type: 'address',
        title: mixins.$t("returnAddress"),
      }
      ],
      staff: [],

      other: [{
        code: 'Remarks',
        type: 'textarea',
        title: mixins.$t("remarks"),
      }]
    },
    // 路由
    routeObjName: 'supplier',
  },
  /**
   * @desc   : 绑定数据-选择页面返回的逻辑处理
   * @author : 王英杰
   * @date   : 2024年3月12日
   */
  chooseData(e) {
    console.log("t", e, this.data.formData);
    let formData = JSON.parse(this.data.formData)
    let code = e.detail.code
    if (code == "supType") { //供应商类别
      return
    }
    let data = e.detail.data.data

    if (code == "serviceCategorie") { //供应商服务类别
      let ids = []
      let names = []
      if (data && data.list) {
        data.list.forEach(element => {
          ids.push(element.id)
          names.push(element.kindName)
        });
      }
      formData.serviceCategorie = ids.join(',')
      formData.serviceCategoriesName = names.join(',')
    }
    if (code == "staffId") { //员工
      formData.staffId = data.id
      formData.staffName = data.name
    }
    if (code == "orgId") { //部门
      formData.orgId = data.id
      formData.orgName = data.name
    }
    if (code == "brandId") { //供应商品牌
      let ids = []
      let names = []
      if (data && data.list) {
        data.list.forEach(element => {
          ids.push(element.brandId)
          names.push(element.brandName)
        });
        let contentObj = this.data.contentObj
        contentObj.main.forEach(element => {
          if (element.code == "brandId") {
            element.datalist = data.list
          }
        });
        this.setData({
          contentObj: contentObj
        })
      }
      formData.brandId = ids.join(',')
      formData.brandName = names.join(',')
      formData.brandIds = ids

    }
    this.setData({
      formData: JSON.stringify(formData)
    })
  },

  /**
   * @desc : 给表单赋值
   * @date : 2024/2/1 15:49
   * @author : 王英杰
   */
  setValuesByEdit(data) {
    data.serviceCategories = data.serviceCategories.join(',')
    data.brandIds = (data.brandIds && data.brandIds.length > 0) ? data.brandIds.split(',') : undefined
    data.addressFull = data.returnAddress
    data.address = {
      address: data.returnAddress
    }
    let contentObj = this.data.contentObj //期初余额 编辑不可编辑
    let index = contentObj.staff.findIndex(t => t.code == 'startAmount')
    if(index != -1){
      contentObj.staff[index].readonly = true
    } 
    //新建的时候 不显示编码 编辑的时候 显示编码
    contentObj.main = [{
      code: 'supCode',
      type: 'textarea',
      title: mixins.$t("supplierCode"),
      readonly: true
    }, { //供应商名称
      code: 'supName',
      type: 'textarea',
      title: mixins.$t("supplierName"),
      required: true,
    }, { //供应商类别
      code: 'supType',
      name: 'supTypeName',
      title: mixins.$t("supplierType"),
      type: 'drop',
      dropType: 'supType',
      // type: 'choose',
      // urlKey: 'chooseSupplierCategory',
      required: true,
      changeObj: {
        [Constants.kindCode.supplierPur]: {
          hide: ['serviceCategorie'],
          visible: ['brandId']
        },
        [Constants.kindCode.supplierOutsourcing]: {
          hide: ['serviceCategorie'],
          visible: ['brandId']
        },
        [Constants.kindCode.supplierService]: {
          hide: ['brandId'],
          visible: ['serviceCategorie']
        }
      },
    }, { //供应品牌
      code: 'brandId',
      name: 'brandName',
      title: mixins.$t("brandId"),
      type: 'choose',
      urlKey: 'chooseBrandy',
      hide:data.supType == Constants.kindCode.supplierService?true:false,
    }, { //服务类别 
      code: 'serviceCategorie',
      name: 'serviceCategoriesName',
      title: mixins.$t("ServiceCategories"),
      type: 'choose',
      urlKey: 'chooseServiceCategory',
      hide:data.supType != Constants.kindCode.supplierService?true:false,
    }, { //联系人
      code: 'contactName',
      type: 'textarea',
      title: mixins.$t("contactName"),
    },
    { //联系电话
      code: 'contactPhone',
      type: 'phone',
      title: mixins.$t("contactPhone"),

    }, {
      code: 'returnAddress',
      type: 'address',
      title: mixins.$t("returnAddress"),
    }
    ],
      data.brandName = data.brandNames
    this.setData({
      contentObj: contentObj,
      formData: JSON.stringify(data)
    })

  },


  // 设置保存参数
  setParams(params) {
    let saveData = JSON.parse(this.data.formData)
    // 修改之后的 值 
    params = Object.assign({}, params, saveData);
    console.log("params", params);
    params.serviceCategories = params.serviceCategorie ? params.serviceCategorie.split(',') : []
    params.brandIds = (params.brandIds && params.brandIds.length > 0) ? params.brandIds : []
    params.returnAddress = saveData.addressFull
    params.makeStaff = app.globalData.user.staffId
    return params
  },

  /**
   * @desc : 保存数据服务
   * @date : 2024/2/1 15:49
   * @author : 王英杰
   */
  saveData() {
    console.log("cnshu", this.data.params);
    if (this.data.formMode == Constants.formMode.edit) { //编辑接口
      return this.excute(this.data.service, this.data.service.update, this.data.params)
    } else { //新建接口
      return this.excute(this.data.service, this.data.service.insert, this.data.params);
    }
  },
  /**
   * @desc : 保存之后的后续操作
   * @date : 2024/5/21 15:49
   * @author : 周兴
   */
  handleSaveData(){
    // 赋值默认的供应商类别
    this.loadInit();
  },

  /**
   * @desc : 页面加载数据方法
   * @date : 2024/2/1 15:49
   * @author : 王英杰
   */
  loadInit() {
    // 标准版：新建供应商类型默认外协供应商，且不能点开；
    //专业版：默认采购供应商，点开是侧拉样式不是跳页（因为不能新建）；
    let contentObj = this.data.contentObj
    let formData = this.data.formData ? JSON.parse(this.data.formData) : {}
    if (this.data.gradeCode == Constants.gradeCode.STD ||
      this.data.formType == Constants.chooseType.outSupplier) { //标准 
      contentObj.main = [{ //供应商名称
        code: 'supName',
        type: 'textarea',
        title: mixins.$t("supplierName"),
        required: true,
      }, { //供应商类别
        code: 'supType',
        name: 'supTypeName',
        title: mixins.$t("supplierType"),
        type: 'drop',
        dropType: 'supType',
        clear:false,
        // type: 'choose',
        // urlKey: 'chooseSupplierCategory',
        required: true,
        readonly: true,
        changeObj: {
          [Constants.kindCode.supplierPur]: {
            hide: ['serviceCategorie'],
            visible: ['brandId']
          },
          [Constants.kindCode.supplierOutsourcing]: {
            hide: ['serviceCategorie'],
            visible: ['brandId']
          },
          [Constants.kindCode.supplierService]: {
            hide: ['brandId'],
            visible: ['serviceCategorie']
          }
        },
      }, { //供应品牌
        code: 'brandId',
        name: 'brandName',
        title: mixins.$t("brandId"),
        type: 'choose',
        urlKey: 'chooseBrandy',
      }, { //服务类别 
        code: 'serviceCategorie',
        name: 'serviceCategoriesName',
        title: mixins.$t("ServiceCategories"),
        type: 'choose',
        urlKey: 'chooseServiceCategory',
      }, { //联系人
        code: 'contactName',
        type: 'textarea',
        title: mixins.$t("contactName"),
      },
      { //联系电话
        code: 'contactPhone',
        type: 'phone',
        title: mixins.$t("contactPhone"),

      }, {
        code: 'returnAddress',
        type: 'address',
        title: mixins.$t("returnAddress"),
      }
      ]

      formData.supType = Constants.kindCode.supplierOutsourcing// "供应商类别-外协"
      formData.supTypeName = mixins.$t("outsourcingSupplier") //"外协供应商"

    } else if (this.data.gradeCode == Constants.gradeCode.PRO) { //专业
      contentObj.main = [{ //供应商名称
        code: 'supName',
        type: 'textarea',
        title: mixins.$t("supplierName"),
        required: true,
      }, { //供应商类别
        code: 'supType',
        name: 'supTypeName',
        title: mixins.$t("supplierType"),
        type: 'drop',
        dropType: 'supType',
        // type: 'choose',
        // urlKey: 'chooseSupplierCategory',
        required: true,
        changeObj: {
          [Constants.kindCode.supplierPur]: {
            hide: ['serviceCategorie'],
            visible: ['brandId']
          },
          [Constants.kindCode.supplierOutsourcing]: {
            hide: ['serviceCategorie'],
            visible: ['brandId']
          },
          [Constants.kindCode.supplierService]: {
            hide: ['brandId'],
            visible: ['serviceCategorie']
          }
        },
      }, { //供应品牌
        code: 'brandId',
        name: 'brandName',
        title: mixins.$t("brandId"),
        type: 'choose',
        urlKey: 'chooseBrandy',
      }, { //服务类别 
        code: 'serviceCategorie',
        name: 'serviceCategoriesName',
        title: mixins.$t("ServiceCategories"),
        type: 'choose',
        urlKey: 'chooseServiceCategory',
      }, { //联系人
        code: 'contactName',
        type: 'textarea',
        title: mixins.$t("contactName"),
      },
      { //联系电话
        code: 'contactPhone',
        type: 'phone',
        title: mixins.$t("contactPhone"),

      }, {
        code: 'returnAddress',
        type: 'address',
        title: mixins.$t("returnAddress"),
      }
      ]
      contentObj.staff = [
        { //采购人员
          code: 'staffId',
          name: 'staffName',
          title: mixins.$t("procureStaff"),
          type: 'choose',
          urlKey: 'chooseStaff',
          required: true,
        }, { //业务部门
          code: 'orgId',
          name: 'orgName',
          title: mixins.$t("orgId"),
          type: 'choose',
          urlKey: 'chooseOrg',
          required: true,
        }, { // todo: 目前 表里 缺这个字段 先不弄
          code: 'startAmount',
          type: 'number',
          title: '初始欠款',
        }
      ]
      formData.supType = Constants.kindCode.supplierPur//"供应商类别-采购"
      formData.supTypeName = mixins.$t("procurementSupplier") //采购供应商" 
    }
    //默认按照 采购供应商的显示显隐
    this.setData({
      contentObj: contentObj,
      formData: JSON.stringify(formData)
    })
    let changeObj = {
      [Constants.kindCode.supplierPur]: {
        hide: ['serviceCategorie'],
        visible: ['brandId']
      },
      [Constants.kindCode.supplierOutsourcing]: {
        hide: ['serviceCategorie'],
        visible: ['brandId']
      },
      [Constants.kindCode.supplierService]: {
        hide: ['brandId'],
        visible: ['serviceCategorie']
      }
    }
    const myComponent = this.selectComponent('#' + this.data.formName);
    // 四个参数（1.contentObj 要改变的对象列表    2. 对象列表需要改变的块名 3.改变块 里的 changeObj 改变规则 4.规则里的 规则名）
    myComponent.defaultvisibleOrHide(contentObj, 'main', changeObj, Constants.kindCode.supplierPur);

    if (this.data.formMode == Constants.formMode.edit) {
      wx.setNavigationBarTitle({
        title: mixins.$t('supplierEdit'),
      })

    } else {
      wx.setNavigationBarTitle({
        title: mixins.$t('supplierAdd'),
      })
      let formData = this.data.formData ? JSON.parse(this.data.formData) : {}
      //采购人员和采购部门默认带出来（当前登录人
      formData.staffId = app.globalData.user.staffId
      formData.orgId = app.globalData.user.orgId
      formData.staffName = app.globalData.user.staffName
      formData.orgName = app.globalData.user.orgName
      this.setData({
        formData: JSON.stringify(formData)
      })
    }
  },
})