<style lang="scss" scoped>
.select-project {
  width: 50%;
}
.row-item {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}
.row-item:last-of-type {
  margin-bottom: 0;
}
.row-item .hint-item {
  width: 24px;
  min-width: 24px;
  align-self: flex-start;
  line-height: 20px;
  height: 20px;
  margin-top: 9px;
}
.row-item .label-item {
  position: relative;
  align-items: flex-start;
  align-self: flex-start;
  line-height: 20px;
  height: 20px;
  margin-top: 10px;
  width: 140px;
  //   min-width: 80px;
  .text-item {
    font-size: 14px;
    width: 120px;
  }
}
.row-item .required-item {
  width: 4px;
  height: 4px;
  border-radius: 2px;
  background: #f45858;
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
}
.row-item .input-item {
  min-width: 480px;
  position: relative;
  // height: 35px;
  .tip {
    font-size: 12px;
    color: tomato;
  }
  .inventory-tags-lists-header {
    background-color: #F8F9FA;
    border: 1px solid #E4E9ED;
    height: 36px;
    line-height: 33px;
    border-radius: 4px 4px 0 0;
    font-weight: bold;
    display: flex;
  }

  .inventory-tags-lists-container {
    border: 1px solid #E4E9ED;
    margin-top: -1px;
    height: 100%;
    padding: 4px 0px;
    border-radius: 0 0 4px 4px;
  }

  .inventory-tags-lists-item {
    width: 100%;
    height: 37px;
    line-height: 37px;
    padding-left: 12px;
    padding-right: 12px;
    display: flex;
    font-size: 14px;
    color: #333;
  }
}
</style>
<template>
  <div class="select-project">
    <a-modal title="账户选择" v-model="showEdit" @ok="handleOk" @cancel="close" width="80%" :confirm-loading="confirmLoading">
      <!-- <span style="margin-bottom:15px">是否同步快手主页</span> -->
      <div class="row-item">
        <div class="hint-item"></div>
        <div class="label-item">
          <div class="text-item">是否同步快手主页</div>
          <!-- <div class="required-item"></div> -->
        </div>
        <div class="input-item" v-if="showEdit">
          <a-form-item>
            <a-switch v-model="shieldBackwardSwitch" />
          </a-form-item>
        </div>
      </div>
       <div class="row-item">
        <div class="hint-item"></div>
        <div class="label-item">
          <div class="text-item">是否同步全部账户</div>
          <!-- <div class="required-item"></div> -->
        </div>
        <div class="input-item" v-if="showEdit">
          <a-form-item>
            <a-switch v-model="isMultiagent" @change="getParticipateList(null)"/>
          </a-form-item>
        </div>
      </div>
      <!-- <treeselect
        :multiple="multiple"
        :disable-branch-nodes="!multiple"
        :branch-nodes-first="true"
        :options="options"
        :load-options="loadOptions"
        placeholder="请选择项目"
        v-model="value"
        :value-consists-of="valueConsistsOf"
        :auto-load-root-options="false"
        :auto-select-descendants="false"
        @select="update"
        @input="emitValue"
        :limit="2"
        :default-options="true"
        :limitText="
          (count) => {
            return '隐藏' + count + '条'
          }
        "
        noChildrenText="该项目下暂无账号"
        :noOptionsText="showLoading"
      /> -->
      <!-- :default-expanded-keys="[2, 3]"
        :default-checked-keys="[5]" -->
      <el-tree
        :data="options"
        show-checkbox
        node-key="id"
        :props="defaultProps"
        :load="loadOptions"
        lazy
        :check-strictly="!isMultiagent"
        ref="tree"
        @check="update"
      >
      </el-tree>
    </a-modal>
  </div>
</template>

<script>
//   @open="getParticipateList"
// import the component
import Treeselect from '@riophae/vue-treeselect'
// import the styles
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'

import { getAction, postAction } from '@/api/manage'
import { mapGetters } from 'vuex'
// We just use `setTimeout()` here to simulate an async operation
// instead of requesting a real API server for demo purpose.
function tqFun(qcArr1) {
  var tempArr = []
  function bbFun(qcArr) {
    for (var i = 0; i < qcArr.length; i++) {
      if (qcArr[i] instanceof Array) {
        bbFun(qcArr[i])
      } else {
        tempArr.push(qcArr[i])
      }
    }
    return tempArr
  }
  return bbFun(qcArr1)
}
let called = false
export default {
  data: () => ({
    defaultProps: {
      children: 'children',
      label: 'label',
      id: 'id',
    },
    shieldBackwardSwitch: false,
    isMultiagent:false,
    showEdit: false,
    value: null,
    valueConsistsOf: 'LEAF_PRIORITY',
    options: [],
    showLoading: 'loading...',
    confirmLoading:false
  }),
  props: {
    //是否多选
    multiple: {
      type: Boolean,
      default() {
        return true
      },
    },
    //判断媒体类型
    request: {
      type: String,
      default() {
        return '2,4'
      },
    },
    //一级请求接口
    reqUrl: {
      type: String,
      default() {
        return '/ctop/projectMember/participateListByMediaId'
      },
    },
    productId:{
      type: Number,
      default() {
        return null
      },
    },
  },
  components: {
    Treeselect,
  },
  watch: {
    $route(n, o) {},
    //   appId: {
    //     handler(n, o) {
    //       console.log(n)
    //       if (n.length == 0) {
    //         if (this.multiple) {
    //           this.value = []
    //         } else {
    //           this.value = ''
    //         }
    //       }
    //     },
    //     deep: true
    //   }
  },
  methods: {
    getCheckedKeys() {
      console.log(this.$refs.tree.getCheckedKeys())
    },
    handleOk(e) {
      this.confirmLoading = true
      var data = this.$refs.tree.getCheckedNodes()
      if(!this.isMultiagent){
        var dataArr = data.map(item=>{
          return {
            accountId:item.id.split('@')[0],
            userName:item.id.split('@')[2],
            userId:item.id.split('@')[1],
          }
        })
        this.showEdit = false
        this.$emit('synchro', {treeData:dataArr,shieldBackwardSwitch:this.shieldBackwardSwitch,isMultiagent:this.isMultiagent})
      }else{
        var dataArr = []
        if(this.productId == 8640280){
          for (let i = 0; i < data.length; i++) {
            getAction('/ctop/userAllocation/getAccountIdListByUserId', {
              userId: data[i].id.split('@')[1],
            }).then((res) => {
              dataArr.push(...res.result.map((item) => {
                return {
                  accountId:item.accountId,
                  userId:data[i].id.split('@')[1],
                }
              }))

               
            })
            
          }
          setTimeout(()=>{
            this.showEdit = false
            this.$emit('synchro', {treeData:dataArr,shieldBackwardSwitch:this.shieldBackwardSwitch,isMultiagent:this.isMultiagent})
          },data.length*600)
        }else{
          dataArr = data.map(item=>{
          
              return {
                accountId:item.id.split('@')[0],
                userId:item.id.split('@')[1],
              }

          })
          this.showEdit = false
          this.$emit('synchro', {treeData:dataArr,shieldBackwardSwitch:this.shieldBackwardSwitch,isMultiagent:this.isMultiagent})
        }
         

      }
      
      // console.log(dataArr)
     
      
    },
    close() {
      // this.$refs.tree.setCheckedKeys([])
      this.shieldBackwardSwitch = false
      this.isMultiagent = false
      this.showEdit = false
    },
    ...mapGetters(['nickname', 'avatar', 'userInfo']),
    update(node, id) {

      
      this.$nextTick(()=>{
          // if(node.children.length>0){

          // }else{
            // getAction('/ctop/userAllocation/getAccountIdListByUserId', {
            //   userId: node.id.split('@')[1],
            // }).then((res) => {
            //   console.log(res)
            //   if (res.code == 0) {
            //       if (res.result.length > 0&&node.children.length == 0) {
            //         node.children = res.result.map((item) => {
            //           return {
            //             id: item.accountId,
            //             label:
            //               (item.userName.length == 2
            //                 ? item.userName + '\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0'
            //                 : item.userName.length == 3
            //                 ? item.userName + '\xa0\xa0\xa0\xa0'
            //                 : item.userName) +
            //               '\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0' +
            //               item.accountId +
            //               '\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0' +
            //               item.authName,
            //             disabled: this.isMultiagent,
            //             children:null
            //           }
            //         })

            //       } else {
            //         node.children = null
            //       }
            //     } else {
            //     }
            // })
          // }


      })
      

    },
    emitValue() {
      // this.$emit('update:appId', this.value)
    },
    loadOptions(node, resolve) {
      // Typically, do the AJAX stuff here.
      // Once the server has responded,
      // assign children options to the parent node & call the callback.
      console.log(node)
      var data = []
      if (node.level == 1) {
        var id = node.key.split('@')[1]
        getAction('/ctop/userAllocation/getAccountIdListByUserId', {
          userId: id,
        }).then((res) => {
          console.log(res)
          if (res.code == 0) {
            if (res.result.length > 0) {
              data = res.result.map((item) => {
                return {
                  id: item.accountId+'@'+id,
                  label:
                    (item.userName.length == 2
                      ? item.userName + '\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0'
                      : item.userName.length == 3
                      ? item.userName + '\xa0\xa0\xa0\xa0'
                      : item.userName) +
                    '\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0' +
                    item.accountId +
                    '\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0' +
                    item.authName,
                  disabled: !this.isMultiagent,
                }
              })
              node.children = data
              console.log(node.children)
              resolve(data)
            } else {
              data = []
              resolve(data)
            }
          } else {
          }
        })
      } else {
        data = []
        resolve(data)
      }
    },
    getParticipateList(productId) {
      
      //我参与的
      //   toutiaoParticipateList
      this.confirmLoading = false
      this.showEdit = true
      getAction('/ctop/userAllocation/getUserIdListByProductId', {
        productId: !!productId?productId:this.productId,
        userId: this.userInfo().id
      }).then((res) => {
        if (res.code == 0) {
          this.options = res.result.map((item) => {
            return {
              id: item.accountId+'@'+item.userId+'@'+item.userName,
              label: item.userId+'-'+item.projectName,
              children: [],
              disabled:this.isMultiagent&&this.productId!=8640280
            }
          })
        } else {
          this.showLoading = '暂无数据'
        }
      })
    },
  },

  mounted() {
    // this.getParticipateList()
  },
}
</script>