<template>
  <div>
    <van-popup
      v-model="postShow"
      class="more-search bg-gray"
      position="right"
      get-container="body"
    >
      <div class="title-layout font-bold font-16">货主</div>
      <van-search
        v-model="keywords"
        placeholder="请输入编码或名称"
        show-action
        @search="onSearch"
      >
        <i slot="left-icon" class="fa fa-search"></i>
        <div slot="action" class="font14" @click="onSearch">搜索</div>
      </van-search>
      <div class="search">
        <div class="searchNum">
          <search-result v-show="searchNumShow" :result-num="searchNum"></search-result>
        </div>
        <van-checkbox class="checkbox" @click="allItemClick()" v-model="isAllChecked">全选</van-checkbox>
      </div>
      <div class="w100 listHeight" ref="scrollRef">
        <van-pull-refresh
          v-model="isRefreshing"
          @refresh="onRefresh">
          <van-list
            v-model="loading"
            :finished="finished"
            finished-text="没有更多了"
            :error.sync="error"
            :offset="10"
            @load="onLoad">
            <!-- <van-radio-group v-model="checked">
              <van-cell-group>
                <van-cell :title="titleInitial(item)" clickable @click="itemClick(item,index)" v-for="(item,index) in postDataList"
                          :key="index">
                  <template #right-icon>
                    <van-radio :name="item.comPartyId" />
                  </template>
                </van-cell>
              </van-cell-group>
            </van-radio-group> -->
            <van-checkbox-group v-model="checkedList">
              <van-cell-group>
                <van-cell :title="titleInitial(item)" clickable @click="itemClick(item,index)" v-for="(item,index) in postDataList"
                          :key="index">
                  <template #right-icon>
                    <van-checkbox :name="item.cellId" />
                  </template>
                </van-cell>
              </van-cell-group>
            </van-checkbox-group>
          </van-list>
        </van-pull-refresh>
      </div>
      <div class="action-bottom">
        <van-button type="default" @click="onCancelClick">取消</van-button>
        <van-button type="info" class="submit" @click="onConfirmClick">确定</van-button>
      </div>
    </van-popup>
  </div>
</template>

<script>
import {getConsignorSetList} from '@/api/common'
import {getResListNum} from '../utils/common'
import SearchResult from './SearchResult'
import { Dialog } from 'vant'

export default {
  name: 'SearchInConsignor',
  components: {SearchResult},
  data() {
    return {
      postShow: false,
      keywords: '上药控股有限公司',
      isRefreshing: false,
      loading: false,
      finished: false,
      error: false,
      searchNum: '0',
      currentPage: 1,
      pageSize: 5,
      postDataList: [],
      checked: '',
      checkedList: [],
      choosedPost: [],
      isAllChecked: false,
      searchNumShow: false
    }
  },
  computed: {
    linkInfo () {
      return this.$store.state.linkInfo
    },
    allChecked () {
      if (this.choosedPost.length === this.postDataList.length) {
        this.isAllChecked = true
      } else {
        this.isAllChecked = false
      }
    }
  },
  props: {
    value: {
      type: Boolean,
      default: false
    },
    customer: {
      type: Array,
      default: () => []
    },
    chinfo: {
      type: Object,
      default: ()=> {
        return {
          goodsId: '',
          supplier: ''
        }
      }
    }
  },
  watch: {
    value(val) {
      this.postShow = val
      if (val) {
        this.postDataList = []
        this.checkedList = []
        this.isAllChecked = false
        this.searchNum = '0'
        this.choosedPost = JSON.parse(JSON.stringify(this.customer))
        // this.checked = !this.customer.comPartyId ? '' : this.customer.comPartyId
        // console.log(this.checked)
        this.customer.forEach((res)=>{
          this.checkedList.push(res.cellId)
        })
        this.currentPage = 1
        this.onLoad()
      }
    },
    postShow (val) {
      if (!val) {
        this.$refs.scrollRef.scrollTop = 0
      }
      this.$emit('input', val)
    }
  },
  methods: {
    // 全选
    allItemClick () {
      const companyList = []
      this.checkedList = []
      this.choosedPost = []
      if (this.isAllChecked) {
        this.postDataList.forEach(item => {
          // console.log(item)
          const model = item
          this.choosedPost.push(item)
          this.checkedList.push(item.cellId)
        })
      }
    },
    /// 标题拼接 <!-- 药厂码/（SAP码）名称 -->
    titleInitial(model) {
      let str = ''
      if (this.isJudgeStrNull(model.companyname)) {
        str = model.companyname + '/'
      }
      if (this.isJudgeStrNull(model.erp_user)) {
        str = str + '('+ model.erp_user + ')'
      }
      if (this.isJudgeStrNull(model.partyOpcode)) {
        str = str + model.partyOpcode
      }
      return str
    },
    onSearch () {
      // if (!this.isJudgeStrNull(this.keywords)) {
      //   Dialog.alert({
      //     title: '温馨提示',
      //     message: '搜索内容为空！'
      //   }).then(() => {
      //   })
      //   return
      // }
      this.keywords = this.keywords.replace(/\s+/g,"")
      this.$refs.scrollRef.scrollTop = 0
      this.currentPage = 1
      this.finished = false
      this.onLoad()
    },
    onCancelClick() {
      this.postShow = false
      this.checkedList = []
      this.$emit('cancleclick')
    },
    onConfirmClick() {
      if (this.choosedPost.length === 0) {
        Dialog.alert({
          title: '温馨提示',
          message: '请选择选项！'
        }).then(() => {
        })
        return
      }
      this.postShow = false
      this.$emit('confirmclick', {
        page: 'consignor',
        value: this.choosedPost
      })
    },
    itemClick(item, index) {
      // this.checked = item.comPartyId
      // this.choosedPost = item
      if(this.checkedList.indexOf(item.cellId) > -1) {
        this.choosedPost.splice(this.checkedList.indexOf(item.cellId),1)
        this.checkedList.splice(this.checkedList.indexOf(item.cellId),1)
      } else {
        this.checkedList.push(item.cellId)
        this.choosedPost.push(item)
      }
      if (this.choosedPost.length === this.postDataList.length) {
        this.isAllChecked = true
      } else {
        this.isAllChecked = false
      }
    },
    onRefresh() {
      // 刷新接口
      // this.postDataList = []
      this.currentPage = 1
      this.isRefreshing = true
      this.finished = false
      this.getPostData()
    },
    onLoad() {
      this.loading = true
      this.getPostData()
    },
    getPostData() {
      let _this = this
      let data = {
        'attr': {
            'empid': _this.linkInfo.userId
        },
        'filters': [
          {
            key: 'companyname',
            opt: 'LIKE',
            type: 'S',
            value: _this.keywords
          }
        ],
        'logic': 'or',
        'sort': 'desc',
        'orderby': 'createon',
        'pageNum': _this.currentPage,
        'pageSize': _this.pageSize
      }
      getConsignorSetList(data).then(rt => {
        if (rt.code === 200) {
          if (_this.currentPage === 1) {
            _this.searchNum = rt.data.length + ''
            this.postDataList = []
          }
          if (this.isJudgeStrNull(_this.keywords)) {
            this.searchNumShow = true
          } else {
            this.searchNumShow = false
          }
          if (this.isRefreshing) {
            // console.log('111111')
            this.postDataList = this.postDataListAction(rt.data)
            _this.searchNum = _this.postDataList.length + ''
          } else if (rt.data || rt.data.length > 0) {
            this.postDataList = this.postDataList.concat(this.postDataListAction(rt.data))
            _this.searchNum = _this.postDataList.length + ''
          }
          if (this.choosedPost.length === this.postDataList.length) {
            this.isAllChecked = true
          } else {
            this.isAllChecked = false
          }
          // 重置刷新提示
          _this.isRefreshing = false
          // 重置加载更多提示
          _this.loading = false
          if (rt.data.length < _this.pageSize) {
            _this.finished = true
          } else {
            // 加载成功后下一页自增1
            _this.currentPage++
            _this.finished = false
          }
        } else {
          _this.$toast(rt.message)
          // _this.$toast('列表获取失败')
          _this.isRefreshing = false
          _this.error = true
          _this.finished = true
        }
        // 加载状态结束
        _this.loading = false
      }).catch(e => {
        _this.$toast('列表获取失败')
        _this.isRefreshing = false
        _this.loading = false
        _this.error = true
        _this.finished = true
      })
    },
    postDataListAction(httpList) {
      const array = []
      httpList.forEach(item => {
        const removeItem = item
        removeItem.cellId = item.id + item.erp_user
        array.push(removeItem)
      })
      return httpList
    },
    /// 判断数值是否为空
    isJudgeStrNull(val) {
      if (val !== null && val !== undefined && val !== '') {
        return true
      }
      return false
    }
  }
}
</script>

<style lang="scss" scoped>
  .more-search {
    width: 75%;
    height: 100%;
    overflow: hidden;
    display: flex;
    flex-direction: column;
  }
  .search{
    background-color: #F5F5F5;
    display: flex;
    padding-right: 10px;
    min-height: 35px;
    .searchNum{
      width: 80%;
    }
    .checkbox{
      width: 20%;
    }
    .content {
      flex: 1;
    }
  }
  .title-layout {
    height: 45px;
    line-height: 45px;
    text-align: center;
    background: white;
    font-size:17px;
    font-weight:500;
    color: #23262A;
  }

  .listHeight {
    flex: 1;
    overflow-x: hidden;
    overflow-y: auto;
  }

  .num-tip {
    padding: 10px;
  }

  .item-layout {
    height: 40px;
    line-height: 40px;
    background: white;
    border-bottom: #dedede 1px solid;
    padding-left: 10px;
  }

  .action-bottom {
    width: 100%;
    display: flex;
    button {
      flex: 1;
    }
  }

  .red-tips {
    color: #fb1c1c;
    font-weight: bold;
  }
</style>
