<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>
      <search-result :result-num="searchNum"></search-result>
      <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-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.comPartyId" />
                  </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 {getOrderCustomerSetList} from '../api/common'
import {getResListNum} from '../utils/common'
import SearchResult from './SearchResult'
import { Dialog } from 'vant'

export default {
  name: 'SearchInClient',
  components: {SearchResult},
  data() {
    return {
      postShow: false,
      keywords: '',
      isRefreshing: false,
      loading: false,
      finished: false,
      error: false,
      searchNum: '0',
      currentPage: 1,
      pageSize: 10,
      postDataList: [],
      postClientIdList: [],
      checked: '',
      checkedList: [],
      choosedPost: []
    }
  },
  computed: {
    linkInfo () {
      return this.$store.state.linkInfo
    }
  },
  props: {
    value: {
      type: Boolean,
      default: false
    },
    // 供应商
    supplier: {
      type: Array,
      default: () => []
    },
    customer: {
      type: Array,
      default: () => []
    },
    // 货主
    consignor: {
      type: Array,
      default: () => []
    },
    chinfo: {
      type: Object,
      default: ()=> {
        return {
          goodsId: '',
          supplier: ''
        }
      }
    }
  },
  watch: {
    value(val) {
      this.postShow = val
      if (val) {
        this.postDataList = []
        this.postClientIdList = []
        this.checkedList = []
        this.searchNum = '0'
        this.choosedPost = JSON.parse(JSON.stringify(this.customer))
        // this.checked = !this.customer.comPartyId ? '' : this.customer.comPartyId
        this.customer.forEach((res)=>{
          this.checkedList.push(res.comPartyId)
        })
        // console.log(this.checked)
        this.currentPage = 1
        this.onLoad()
      }
    },
    postShow (val) {
      if (!val) {
        this.$refs.scrollRef.scrollTop = 0
      }
      this.$emit('input', val)
    }
  },
  methods: {
    /// 标题拼接 <!-- 药厂码/（SAP码）名称 -->
    titleInitial(model) {
      let titleStr = model.companyname + '/' +model.comPartyId + '/(' + model.partyOpcode + ')/' + model.partyName
      return titleStr
    },
    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.$emit('cancleclick')
    },
    onConfirmClick() {
      if (!this.choosedPost.length === 0) {
        Dialog.alert({
          title: '温馨提示',
          message: '请选择选项！'
        }).then(() => {
        })
        return
      }
      this.postShow = false
      this.$emit('confirmclick', {
        page: 'client',
        value: this.choosedPost
      })
    },
    itemClick(item, index) {
      // this.checked = item.comPartyId
      // this.choosedPost = item
      if(this.checkedList.indexOf(item.comPartyId) > -1) {
        this.choosedPost.splice(this.checkedList.indexOf(item.comPartyId),1)
        this.checkedList.splice(this.checkedList.indexOf(item.comPartyId),1)
      } else {
        this.checkedList.push(item.comPartyId)
        this.choosedPost.push(item)
      } 
    },
    onRefresh() {
      // 刷新接口
      // this.postDataList = []
      this.currentPage = 1
      this.isRefreshing = true
      this.finished = false
      this.getPostData()
    },
    onLoad() {
      this.getPostData()
    },
    getPostData() {
      let _this = this
      const companyList = []
      _this.consignor.forEach(item => {
        const removeItem = {
          'beforeP': item.db_source,
          'middleP': process.env.appRealDb,
          'afterP': this.getSupplierArray(item.id),
          'saler': item.erp_user,
          'companyname': item.companyname,
          'companynameId': item.id
        }
        companyList.push(removeItem)
      })
      // _this.consignor.forEach(item => {
      //   const removeItem = {
      //     'beforeP': 'erp_test_shaphar',
      //     'middleP': process.env.appRealDb,
      //     'afterP': '508',
      //     'saler': '23528'
      //   }
      //   companyList.push(removeItem)
      // })
      let data = {
        'customer': _this.keywords,
        'list': companyList,
        'start': _this.currentPage,
        'length': _this.pageSize
      }
      _this.loading = true
      getOrderCustomerSetList(data).then(rt => {
        if (rt.code === '1') {
          if (_this.currentPage === 1) {
           _this.searchNum = getResListNum(rt.msg)
            this.postDataList = []
            this.postClientIdList = []
          }
          if (this.isRefreshing) {
            this.postClientIdList = []
            this.postDataList = this.deleteRepeatAction(rt.data)
            // this.postDataList = rt.data
          }
          else if (!!rt.data || rt.data.length > 0) {
            // this.postDataList = this.postDataList.concat(rt.data)
            this.postDataList = this.postDataList.concat(this.deleteRepeatAction(rt.data))
          }
          // _this.postDataListSetAction(rt.data)
          // 重置刷新提示
          _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.msg)
          // _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
      })
    },
    // 获取供应商数组ID
    getSupplierArray (companynameId) {
      const supplierList = []
      this.supplier.forEach(item => {
        if (item.companynameId === companynameId) {
          supplierList.push(item.org)
        }
      })
      return supplierList
    },
    // 客户去重postClientIdList
    deleteRepeatAction (httpArray) {
      const clientIdArray = []
      httpArray.forEach(item => {
        const removeItem = item
        if (this.postClientIdList.indexOf(item.comPartyId) > -1) {
        } else {
          this.postClientIdList.push(item.comPartyId)
          clientIdArray.push(item)
        }
      })
      return clientIdArray
    },
    /// 判断数值是否为空
    isJudgeStrNull(val) {
      if (val !== null && val !== undefined && val !== '') {
        return true
      }
      return false
    }
  }
}
</script>

<style lang="scss" scoped>
  .content {
    background-color: #F5F5F5;
  }
  .more-search {
    width: 75%;
    height: 100%;
    overflow: hidden;
    display: flex;
    flex-direction: column;
  }
  .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>
