/*******************************************************************************
 * Copyright(c) 2021 dongke All rights reserved. / Confidential
 * 类的信息：
 *		1.程序名称：
 *		2.功能描述：多选下拉组件
 * 编辑履历：
 *		作者				日期					版本				修改内容
 *		姜永辉		  2022-5-05		  1.00		   	新建
 *******************************************************************************/
const api = require('../../../utils/api');
const app = getApp()
const Constants = require('../../../utils/Constants');
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    /**
     *是否在搜索顶部加一个高度
    */
    Top_Height_Flag: {
      type: Boolean,
      value: false
    },
    /**
      *q
     */
    typeName: {
      type: String,
      value: 'org'
    },
    docName: {
      type: String,
      value: ''
    },
    ids: {
      type: Array,
      value: [],
      observer: function (newVal) {
        if (newVal && newVal.length > 0) {
          this.setData({
            count: newVal.length,
            label_title: '已选(' + newVal.length + ')'
          })
        } else {
          this.setData({
            label_title: '已选'
          })
        }
      }
    },
    jobIds: {
      type: Array,
      value: []
    },
    //是否显示标识，显示后在加载数据
    show: {
      type: Boolean,
      value: false,
      observer: function (newVal) {
        let show = this.properties.show
        //显示后在加载数据
        if (!show) {
          return
        }
        // 给类型赋值
        this.setDataSource();
        let datalists = this.data.datalists;
        let datalist = datalists[this.data.typeName] || []
        // if (datalist.length == 0) {
        if (!datalists[this.data.typeName] || datalists[this.data.typeName].length == 0) {
          let DataSourceCode = this.data.DataSourceCode
          let typeName = this.data.typeName
          this.getdata(DataSourceCode).then(res => {
            let list = res.data
            if (list == null || list.length <= 0) return
            let datalist = []
            // 部门
            if (typeName === 'org') {
              list.forEach(item2 => {
                let item = {
                  id: item2.id,
                  name: item2.orgName,
                  checked: false
                }
                datalist.push(item)
              })
              //业务员
            } else if (typeName === 'staff') {
              list.forEach(item2 => {
                let item = {
                  id: item2.id,
                  name: item2.staffName, 
                  checked: false
                }
                datalist.push(item)
              })

            }
            // 角色
            else if (typeName === 'role') {
              list.forEach(item2 => {
                let item = {
                  id: item2.id,
                  name: item2.name,
                  qvUserid: item2.qvUserid,
                  checked: false
                }
                datalist.push(item)
              })

            }
            else if (typeName === 'salesChannel') {
              //渠道
              list.forEach(item2 => {
                let item = {
                  id: item2.id,
                  name: item2.name,
                  checked: false
                }
                datalist.push(item)
              })
            }
            else if (typeName === 'loseReason') {
              list.forEach(item2 => {
                let item = {
                  id: item2.id,
                  name: item2.name,
                  checked: false
                }
                datalist.push(item)
              })
            }
            else if (typeName === 'warehouse') {
              list.forEach(item2 => {
                let item = {
                  id: item2.id,
                  name: item2.name,
                  checked: false
                }
                datalist.push(item)
              })
            }
            else if (typeName === 'brand') {
              list.forEach(item2 => {
                let item = {
                  id: item2.id,
                  name: item2.name,
                  checked: false
                }
                datalist.push(item)
              })
            }
            else if (typeName === 'serviceCategories') {
              list.forEach(item2 => {
                let item = {
                  id: item2.code,
                  name: item2.name,
                  checked: false
                }
                datalist.push(item)
              })
            }
            let finallist = [...datalist]
            datalists[this.data.typeName] = [...datalist]
            this.setData({
              datalists: datalists,
              finallist: finallist
            })
            this.setCheck()
          })
        }
      }
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    ids: [],
    DataSourceCode: '',
    // 是否点击清除按钮
    isClickClear: false,
    datalists: {},
    finallist: [],
    condition: '',
    dataValue: '',
    name: '',
    label_title: '可选',
    count: 0,
    radio: null,
    defaultCheackFlag: false //默认选中数据
  },
  lifetimes: {
    attached: function () {
      let DataSourceCode = ''
      let typeName = this.data.typeName
      let docName = this.data.docName
      let name = ''
      // 部门
      if (typeName === 'org') {
        DataSourceCode = 'org'
        name = '业务部门'
      }
      //业务员
      if (typeName === 'staff') {
        DataSourceCode = 'staff'
        name = '业务员'
      }
      //销售渠道
      if (typeName === 'salesChannel') {
        DataSourceCode = 'salesChannel'
        name = '渠道'
      }
      //仓库
      if (typeName === 'warehouse') {
        DataSourceCode = 'warehouse'
        name = '仓库'
      }
      //品牌
      if (typeName === 'brand') {
        DataSourceCode = 'brand'
        name = '品牌'
      }
      //服务类别
      if (typeName === 'serviceCategories') {
        DataSourceCode = 'serviceCategories'
        name = '服务类别'
      }
      this.setData({
        DataSourceCode: DataSourceCode
      })
    },
    detached: function () {
      // 在组件实例被从页面节点树移除时执行
    },
  },

  /**
   * 组件的方法列表
   */
  methods: {
    /**
     * @desc   : 值改变
     * @author : 周兴
     * @date   : 2024/1/26 11:46
     */
    onChange(e) {
      let datalists = this.data.datalists
      let datalist = datalists[this.data.typeName] || []
      if (datalist) {
        datalist.forEach(it => {
          it.checked = false;
        })
        if (e.detail && e.detail.length > 0) {
          e.detail.forEach(it => {
            if (datalist[it]) {
              datalist[it].checked = true;
            }
          })
        }
        this.setData({
          radio: e.detail,
          datalists: datalists,
        })
      }
    },
    /**
     * @desc   : 给类型赋值
     * @author : 周兴
     * @date   : 2024/1/26 11:46
     */
    setDataSource() {
      let DataSourceCode = ''
      let typeName = this.data.typeName
      let docName = this.data.docName
      let name = ''
      // console.log('typeName', typeName);
      // 部门
      if (typeName === 'org') {
        DataSourceCode = 'org'
        name = '业务部门'
      }
      //业务员
      if (typeName === 'staff') {
        DataSourceCode = 'staff'
        name = '业务员'
      }
      //角色
      if (typeName === 'role') {
        DataSourceCode = 'role'
        name = '角色'
      }
      //销售渠道
      if (typeName === 'salesChannel') {
        DataSourceCode = 'salesChannel'
        name = '渠道'
      }
      //仓库
      if (typeName === 'warehouse') {
        DataSourceCode = 'warehouse'
        name = '仓库'
      }
      //品牌
      if (typeName === 'brand') {
        DataSourceCode = 'brand'
        name = '品牌'
      }
      //服务类别
      if (typeName === 'serviceCategories') {
        DataSourceCode = 'serviceCategories'
        name = '服务类别'
      }

      this.setData({
        DataSourceCode: DataSourceCode
      })
    },
    setCheck() {
      let ids = this.data.ids
      let datalists = this.data.datalists
      let dataList = datalists[this.data.typeName]
      dataList.forEach(it => {
        if (ids.some(it2 => it2 == it.id)) {
          it.checked = true
        }
      })
      this.setData({
        datalists: datalists
      })
    },
    /**
     * 查询数据
     * @param {*} e 
     */
    getdata: function (DataSourceCode) { 
      let param = {
        dataSourceCode: DataSourceCode
      }
      if (DataSourceCode === 'org' || DataSourceCode === 'staff') {
        param.docName = this.data.docName
      }

      if (DataSourceCode === 'staff' && this.data.jobIds && this.data.jobIds.length > 0) {
        param.jobIds = this.data.jobIds
      }
      if (DataSourceCode === 'warehouse') {
        param.cpId = app.globalData.user.cpId
      }

      return new Promise((resolve, reject) => {
        api.request(Constants.BASIC_COMMON_API + 'get_init_data', 'POST', param).then(res => {
          if (res.data.code === 200) {
            resolve(res.data)
          } else {
            reject(res.data)
          }
        })
      })
    },
    /**
     * 关闭弹窗
     */
    onClose: function () {
      this.setData({
        show: false
      })
      // 为了关闭外面的下拉
      this.triggerEvent('muticlose')
    },
    /**
     * 勾选或者勾选
     */
    checkItem: function (e) {
      let datalists = this.data.datalists
      let datalist = datalists[this.data.typeName]
      let finallist = this.data.finallist
      let id = e.target.dataset.id
      let count = this.data.count
      datalist.forEach(item => {
        if (item.id === id) {
          item.checked = !item.checked
        }
      })
      // 原列表
      finallist.forEach(item => {
        if (item.id === id) {
          // 勾选
          if (item.checked) {
            count++
          }
          // 去掉勾选
          else {
            count--
          }
          //  item.checked = item.checked
        }
      })

      let label_title = this.data.label_title
      if (count === 0) {
        label_title = '可选'
      } else {
        label_title = '已选(' + count + ')'
      }

      this.setData({
        datalists: datalists,
        finallist: finallist,
        count: count,
        label_title: label_title
      })
    },
    /**
     * 过滤数据
     * @param {*} e 
     */
    onChange_input: function (e) {
      let finallist = this.data.finallist
      if (finallist === null || finallist.length === 0) return
      // 复制
      finallist = [...finallist]
      let condition = this.data.condition
      let datalist = []
      finallist.forEach(item => {
        if (item.name.indexOf(condition) >= 0) {
          datalist.push(item)
        }
      })
      let datalists = this.data.datalists
      datalists[this.data.typeName] = datalist
      this.setData({
        datalists: datalists
      })
    },
    /**
     * 焦点离开事件
     */
    blur_input() {
      let datalist = this.data.datalists[this.data.typeName]
      if (datalist.length <= 0) {
        this.reset()
      }
    },
    /**
     * 重置
     */
    reset: function () {
      let datalists = this.data.datalists
      let finallist = this.data.finallist

      if (finallist == null || finallist.length === 0) return
      // datalist.forEach(item => {
      //   item.checked = false
      // })
      finallist.forEach(item => {
        item.checked = false
      })
      let datalist = [...finallist]
      datalists[this.data.typeName] = datalist
      this.setData({
        finallist: finallist,
        datalists: datalists,
        condition: '',
        count: 0,
        radio: [],
        label_title: '可选',
        defaultCheackFlag: true
      })
    },
    /**
     * @desc : 清空所有数据
     * @author : 周兴
     * @date : 2024/1/26 12:16
     */
    clearAll() {
      // 清空控件
      this.setData({
        datalists: {},
        finallist: [],
        condition: '',
        isClickClear: true,
        dataValue: '',
        count: 0,
        radio: [],
        label_title: '可选'
      })
    },
    /**
     * 清除数据
     */
    clear() {
      let finallist = this.data.finallist
      // 清空勾选框
      finallist.forEach(item => {
        item.checked = false
      })

      let datalist = [...finallist]
      this.triggerEvent('commit', {
        ids: '',
        names: '',
        list: []
      })
      let datalists = this.data.datalists
      datalists[this.data.typeName]
      // 清空控件
      this.setData({
        datalists: datalists,
        finallist: finallist,
        condition: '',
        isClickClear: true,
        dataValue: '',
        count: 0,
        label_title: '可选'
      })
    },
    /**
     * 提交
     */
    commit: function () {
      let datalist = this.data.finallist
      if (datalist == null || datalist.length === 0) return
      let ids = []
      let names = []
      datalist.forEach(item => {
        if (item.checked) {
          ids.push(item.id)
          names.push(item.name)
        }
      })
      this.triggerEvent('commit', {
        ids: ids.join(','),
        names: names.join(','),
        list: datalist.filter(it => it.checked),
        idList: ids,
      })
      this.setData({
        dataValue: names,
        show: false
      })
    },
  }
})