<template>
  <NavBar />
  <view class="container">

    <view class="title">
      <PageTitle :title="$t('home.customer.title')" />
    </view>
    <view style="margin-top: 20px">
      <Segmented
          styleType="text"
          fontSize="16px"
          gap="6px"
          :current="current"
          :values="items"
          @clickItem="onClickItem"
          inActiveColor="#999999"
          activeColor="#000"
      ></Segmented>
    </view>

    <view style="margin-top: 20px">
      <view class="search">
        <input class="searchInput" v-model="queryLeadUserListParams.searchVal" :placeholder="$t('home.customer.sellPage.name')+'/'+$t('home.customer.sellPage.email')">
        <button class="btn primaryButton" @click="search">
          <image src="/static/search.svg" mode="aspectFit" style="width: 14px;height: 14px"></image>
          <text class="filterText">{{ $t('form.search') }}</text>
        </button>
      </view>
      <view class="search2">
        <button class="btn primaryButton" @click="openFilter">
          <image src="/static/filtrate.svg" mode="aspectFit" style="width: 20px;height: 20px"></image>
          <text class="filterText">{{ $t('common.filter') }}</text>
        </button>
        <!--      <button class="btn primaryButton">-->
        <!--        <image src="/static/architectureDiagram.svg" mode="aspectFit" style="width: 20px;height: 20px"></image>-->
        <!--        <text class="filterText">{{ $t('common.architectureDiagram') }}</text>-->
        <!--      </button>-->
        <!--      <button class="btn primaryButton">-->
        <!--        <image src="/static/export.svg" mode="aspectFit" style="width: 20px;height: 20px"></image>-->
        <!--        <text class="filterText">{{ $t('common.export') }}</text>-->
        <!--      </button>-->
      </view>

      <scroll-view style="height: calc(100vh - 300px);" scroll-y="true" @scrolltolower="scrolltolowerQuery" >
        <view class="item" v-for="user in leadUserList" :key="user.id">
          <view class="top">
            <view class="itemTitle">
<!--              <image class="title-bg" src="/static/titleIcon2.svg" mode="aspectFit"></image>-->
              <view class="title-bg">
                <text class="title-text">{{ user.id }}</text>
              </view>
            </view>
          </view>
          <view class="operate">
            <view class="primaryButton operateBtn" style="background: rgba(41, 187, 228, 0.14);margin-right: 4px;" @click="openAllotPopup(user.id)">
              <view style="display: flex;align-items: center;height: 27px;gap: 4px;">
                <image src="/static/distribution.svg" mode="aspectFit" style="width: 15px;height: 15px;margin-top: 2px;"></image>
                <text class="filterText" style="color: rgba(41, 187, 228, 1);">{{ $t('home.customer.sellPage.customerDistribution') }}</text>
              </view>
            </view>

            <view  class="primaryButton operateBtn" @click="openAllotPopup3(user)"
                     v-bind:class="{ 'status0': user.followStatus==0,'status1': user.followStatus==1,'status2': user.followStatus==2,'status3': user.followStatus==3,'status4': user.followStatus==4,'status5': user.followStatus==5 }">
              <view style="display: flex;align-items: center;height: 27px;gap: 4px;">
                <image :src="'/static/customer/edit'+user.followStatus+'.svg'" mode="aspectFit" style="width: 15px;height: 15px"></image>
                <text class="filterText" v-show="user.followStatus==0">{{ $t('home.customer.sellPage.followStatus0') }}</text>
                <text class="filterText" v-show="user.followStatus==1">{{ $t('home.customer.sellPage.followStatus1') }}</text>
                <text class="filterText" v-show="user.followStatus==2">{{ $t('home.customer.sellPage.followStatus2') }}</text>
                <text class="filterText" v-show="user.followStatus==3">{{ $t('home.customer.sellPage.followStatus3') }}</text>
                <text class="filterText" v-show="user.followStatus==4">{{ $t('home.customer.sellPage.followStatus4') }}</text>
                <text class="filterText" v-show="user.followStatus==5">{{ $t('home.customer.sellPage.followStatus5') }}</text>
              </view>
            </view>
<!--            <view class="other"></view>-->
          </view>
          <uni-collapse class="box" style="margin-top: 12px" >
            <uni-collapse-item title-border="none" :show-arrow="false" :border="false" :open="user.if_show" :disabled="true">
              <template v-slot:title>
                <view class="row" v-show="filterColumns.id">
                  <view class="column">ID</view>
                  <view class="value">{{ user.id }}</view>
                </view>

                <view class="row" v-show="filterColumns.user_code">
                  <view class="column">{{ filterColumns.user_code?.title }}</view>
                  <view class="value">{{ user.user_code }}</view>
                </view>

                <view class="row" v-show="filterColumns.email">
                  <view class="column">{{ filterColumns.email?.title }}</view>
                  <view class="value">{{ user.email }}</view>
                </view>

                <view class="bottomItem" v-show="!user.if_show" style="padding-bottom: 8px">
                  <text @click="showItem(user)">{{ $t('home.customer.sellPage.open') }}</text>
                  <image @click="showItem(user)" src="/static/openIcon.svg" mode="aspectFit" style="width: 14px;height: 8px"></image>
                </view>
              </template>
              <view class="content" style="padding-bottom: 8px">
                <view class="row" v-show="filterColumns.user_name">
                  <view class="column">{{ filterColumns.user_name?.title }}</view>
                  <view class="value">{{ user.user_name }}</view>
                </view>
                <view class="row" v-show="filterColumns.customer_type">
                  <view class="column">{{ filterColumns.customer_type?.title }}</view>
                  <view class="value">{{ user.customer_type }}</view>
                </view>
                <view class="row" v-show="filterColumns.phone">
                  <view class="column">{{ filterColumns.phone?.title }}</view>
                  <view class="value">{{ user.phone }}</view>
                </view>
                <view class="row" v-show="filterColumns.status">
                  <view class="column">{{ filterColumns.status?.title }}</view>
                  <view class="value">{{ user.status }}</view>
                </view>
                <view class="row" v-show="filterColumns.org_name">
                  <view class="column">{{ filterColumns.org_name?.title }}</view>
                  <view class="value">{{ user.org_name }}</view>
                </view>

                <view class="bottomItem">
                  <text @click="hideItem(user)">{{ $t('home.customer.sellPage.packUp') }}</text>
                  <image @click="hideItem(user)" src="/static/packUpIcon.svg" mode="aspectFit" style="width: 14px;height: 8px"></image>
                </view>
              </view>

            </uni-collapse-item>
          </uni-collapse>
        </view>
        <Spin v-show="loading" />
        <view class="inTheEnd" v-show="inTheEnd">{{ $t('common.inTheEnd') }}</view>
        <view class="inTheEnd" v-show="noData">{{ $t('common.noData') }}</view>
        <view style="height: 20px;width: 100%;"></view>
      </scroll-view>
    </view>




    <uni-popup ref="popup" background-color="#fff" type="bottom">
      <view style="padding: 37px 0;">
        <view class="filterRow" v-show="filterColumns.user_code?.ifFilter">
          <view class="filterTitle">
            <text>{{ filterColumns.user_code?.title }}</text>
          </view>
          <input class="filterInput" v-model="queryLeadUserListParams.userCode" :placeholder="$t('form.pleaseEnter')">
        </view>
        <view class="filterRow" v-show="filterColumns.user_name?.ifFilter">
          <view class="filterTitle">
            <text>{{ filterColumns.user_name?.title }}</text>
          </view>
          <input class="filterInput" v-model="queryLeadUserListParams.userName" :placeholder="$t('form.pleaseEnter')">
        </view>
        <view class="filterRow" v-show="filterColumns.followStatus?.ifFilter">
          <view class="filterTitle">
            <text>{{ filterColumns.followStatus?.title }}</text>
          </view>
          <uni-data-select
              :placeholder="$t('form.pleaseSelect')"
              :localdata="statusOptions"
              v-model="queryLeadUserListParams.followStatus"
              placement="top"
          >
          </uni-data-select>
        </view>
        <view style="display: flex;gap: 12px;padding: 14px 16px;">
          <buttom class="btn secondaryButton" @click="reset">
            {{ $t('home.customer.sellPage.reset') }}
          </buttom>
          <buttom class="btn primaryButton" @click="search">
            {{ $t('home.customer.sellPage.confirm') }}
          </buttom>
        </view>
      </view>
    </uni-popup>

    <uni-popup ref="popup2" background-color="#fff" type="bottom">
      <view style="padding: 27px 0;">
        <view class="allotRow">
<!--          <view class="filterTitle">-->
<!--            <text>{{ $t('home.customer.sellPage.org') }}</text>-->
<!--            <uni-data-select-->
<!--                :placeholder="$t('form.pleaseSelect')"-->
<!--                :localdata="orgOptions"-->
<!--                v-model="org"-->
<!--                placement="top"-->
<!--            >-->
<!--            </uni-data-select>-->
<!--            <view>-->

<!--            </view>-->
<!--          </view>-->
          <view class="allotItem">
            <input class="searchInput" v-model="querySaleUserListParams.name" :placeholder="$t('home.customer.sellPage.name')">
            <button class="btn primaryButton" @click="querySaleUserList">
              <image src="/static/search.svg" mode="aspectFit" style="width: 14px;height: 14px"></image>
              <text class="filterText">{{ $t('form.search') }}</text>
            </button>
          </view>

          <view class="userBox">
            <uni-data-checkbox selectedColor="#29BBE4" selectedTextColor="#333333" :localdata="userOptions" v-model="saveAssignUserParams.saleId" :wrap="true" mode="list"/>
          </view>

          <view class="operateBox">
            <button class="btn secondaryButton" @click="this.$refs.popup2.close()">
              {{ $t('common.cancelText') }}
            </button>
            <button class="btn primaryButton" @click="handleSaveAssignUser" :disabled="saveAssignUserDisabled">
              <image v-show="btnLoading" src="/static/loadingCircle.svg" mode="aspectFit" style="width: 16px; height: 16px"></image>
              {{ $t('form.save') }}
            </button>
          </view>

        </view>
      </view>
    </uni-popup>

    <uni-popup ref="popup3" background-color="#fff" type="bottom">
      <view class="popup3View">

        <view class="row">
          <view class="filterLabel">
            {{ $t('home.customer.sellPage.name') }}
          </view>
          <view class="filterValue">
            {{ leadUser.user_name }}
          </view>
        </view>

        <view class="row">
          <view class="filterLabel">
            {{ $t('home.customer.sellPage.phone') }}
          </view>
          <view class="filterValue">
            {{ leadUser.phone }}
          </view>
        </view>

        <view class="row">
          <view class="filterLabel">
            {{ $t('home.customer.sellPage.email') }}
          </view>
          <view class="filterValue">
            {{ leadUser.email }}
          </view>
        </view>

        <view class="row">
          <view class="filterLabel">
            {{ $t('home.customer.sellPage.country') }}
          </view>
          <view class="filterValue">
            {{ leadUser.country_text }}
          </view>
        </view>

        <view class="row">
          <view class="filterLabel">
            {{ $t('home.customer.sellPage.status') }}
          </view>
          <uni-data-select
              :placeholder="$t('form.pleaseSelect')"
              :localdata="statusOptions"
              v-model="saveFollowRecordParams.status"
              placement="top"
          >
          </uni-data-select>
        </view>

<!--        <view class="row">-->
<!--          <view class="filterLabel">-->
<!--            {{ $t('home.customer.sellPage.numberOfContacts') }}-->
<!--          </view>-->
<!--          <input style="background: #F7F8FA;height: 35px;padding-left: 13px;">-->
<!--        </view>-->

        <view class="row">
          <view class="filterValue">
            {{ $t('home.customer.sellPage.remark') }}
          </view>
          <textarea v-model="saveFollowRecordParams.remark" style="background: #F7F8FA;width: 100%">

          </textarea>
        </view>

        <view class="operateBox">
          <button class="btn secondaryButton" @click="this.$refs.popup3.close()">
            {{ $t('common.cancelText') }}
          </button>
          <button class="btn primaryButton" @click="handleSaveFollowRecord" :disabled="saveFollowRecordDisabled">
            <image v-show="btnLoading" src="/static/loadingCircle.svg" mode="aspectFit" style="width: 16px; height: 16px"></image>
            {{ $t('form.save') }}
          </button>
        </view>

      </view>
    </uni-popup>
  </view>
</template>

<script>
import Segmented from '@/pages/components/segmented/index.vue';
import UniCollapse from "../../../uni_modules/uni-collapse/components/uni-collapse/uni-collapse.vue";
import UniDataSelect from "../../../uni_modules/uni-data-select/components/uni-data-select/uni-data-select.vue";
import { queryLeadUserList, querySaleUser, saveAssignUser, saveFollowRecord  } from '@/services/customer/sell.ts';
import { UserLanguage, customerMenu } from '@/utils/const';
import { getFilterColumns, queryMenuList } from '@/services/home/home.ts';

export default {
  data() {
    return{
      qcc_page_id:106,
      filterColumns:{},
      loading:false,
      current: 0,
      items: [],
      itemsLink: [],
      inTheEnd:false,
      noData:false,
      totalRecords:0,
      queryLeadUserListParams:{
        searchVal:"",
        curr_page:1,
        page_size:5,
        followStatus:undefined,
        userCode:"",
        userName:"",
      },
      saveAssignUserParams:{
        id:undefined,
        saleId:undefined
      },
      saveFollowRecordParams:{
        id:undefined,
        status:undefined,
        remark:undefined
      },
      leadUserList:[],
      leadUser:{},
      statusOptions:[{text:this.$t('home.customer.sellPage.followStatus0'),value:"0"},{text:this.$t('home.customer.sellPage.followStatus1'),value:"1"},{text:this.$t('home.customer.sellPage.followStatus2'),
        value:"2"},{text:this.$t('home.customer.sellPage.followStatus3'),value:"3"},{text:this.$t('home.customer.sellPage.followStatus4'),value:"4"},{text:this.$t('home.customer.sellPage.followStatus5'),value:"5"}],
      orgOptions:[],
      querySaleUserListParams:{
        name:""
      },
      userOptions:[],
      saveAssignUserDisabled:true,
      saveFollowRecordDisabled:true,
      btnLoading: false

    }
  },
  methods:{
    async getMenuListData() {
      const res = await queryMenuList();
      if (res && res.code === 0) {
        const menuList = [];
        for (var i = 0; i < res.data.length; i++) {
          const { saleRouteKey } = res.data[i]
          if (saleRouteKey == 'customer') {
            if (res.data[i].children.length>0){
              let index = 0;
              for (let j = 0; j < res.data[i].children.length; j++) {
                if (res.data[i].children[j].saleRouteKey !=null && res.data[i].children[j].saleRouteKey !=''){
                  this.items.push(res.data[i].children[j].name)
                  this.itemsLink.push(customerMenu[res.data[i].children[j].saleRouteKey])
                  if (res.data[i].children[j].saleRouteKey == 'sell'){
                    this.current = index
                  }
                  index++
                }
              }
            }
          }
        }
      }
    },
    onClickItem(e){
      if (this.current != e.currentIndex) {
        uni.navigateTo({url: this.itemsLink[e.currentIndex]});
      }
    },
    search(){
      this.queryLeadUserListParams.curr_page = 1
      this.queryLeadUserListParams.page_size = 5
      this.queryUserList()
    },
    async queryUserList() {
      this.leadUserList = []
      this.loading=true
      this.$refs.popup.close();
      const res = await queryLeadUserList({
        curr_page: this.queryLeadUserListParams.curr_page,
        page_size: this.queryLeadUserListParams.page_size,
        qcc_fuzzy_search: this.queryLeadUserListParams.searchVal,
        followStatus: this.queryLeadUserListParams.followStatus,
        user_code: this.queryLeadUserListParams.userCode,
        user_name: this.queryLeadUserListParams.userName,
      });
      if (res && res.code === 0) {
        let data = res.data;
        this.leadUserList = data.records
        this.totalRecords = data.totalRecords
      }
      if (this.leadUserList == null || this.leadUserList.length == 0){
        this.noData = true
      }else {
        this.noData = false
      }
      this.loading=false
    },
    async getFilterColumns(){
      const res = await getFilterColumns({
        qcc_page_id: this.qcc_page_id,
        qcc_language: UserLanguage
      });
      if (res && res.code === 0) {
        let data = res.data
        for (let i = 0; i < data.length; i++) {
          this.filterColumns[data[i].field]=data[i]
        }
      }
    },
    async querySaleUserList(){
      const res = await querySaleUser({
        name: this.querySaleUserListParams.name,
      });
      if (res && res.code === 0) {
        this.saveAssignUserParams.saleId=undefined
        this.userOptions = res.data?.map((user) => ({
          text: user.name,
          value: user.id
        }));
      }
    },
    showItem(user) {
      user.if_show = true;
    },
    hideItem(user) {
      user.if_show = false;
    },
    openFilter() {
      this.$refs.popup.open()
    },
    reset(){
      this.queryLeadUserListParams.userCode = ""
      this.queryLeadUserListParams.userName = ""
      this.queryLeadUserListParams.followStatus = null
    },
    openAllotPopup(id){
      this.$refs.popup2.open()
      this.querySaleUserList()
      this.saveAssignUserParams.id = id
    },
    async handleSaveAssignUser(){
      this.btnLoading = true;
      const res = await saveAssignUser(this.saveAssignUserParams);
      this.btnLoading = false;
      if (res && res.code === 0) {
        this.$refs.popup2.close()
        this.$cusModal.showModal({
          type: 'message',
          status: 'success',
          contentText: res.msg ?? this.$t('common.success.action'),
          onClose() {
            uni.navigateBack();
          }
        });
      } else {
        this.$cusModal.showModal({
          type: 'message',
          status: 'warning',
          contentText: res.msg ?? this.$t('common.error.sysError')
        });
      }
    },
    openAllotPopup3 (user){
      this.saveFollowRecordParams.id = user.id
      this.saveFollowRecordParams.status = user.followStatus
      this.saveFollowRecordParams.remark = user.followRemark
      this.leadUser = user
      this.$refs.popup3.open()
    },
    async handleSaveFollowRecord(){
      this.btnLoading = true;
      const res = await saveFollowRecord(this.saveFollowRecordParams);
      this.btnLoading = false;
      if (res && res.code === 0) {
        this.$refs.popup3.close()
        this.$cusModal.showModal({
          type: 'message',
          status: 'success',
          contentText: res.msg ?? this.$t('common.success.action'),
          onClose() {
            uni.navigateBack();
          }
        });
      } else {
        this.$cusModal.showModal({
          type: 'message',
          status: 'warning',
          contentText: res.msg ?? this.$t('common.error.sysError')
        });
      }
    },
    async scrolltolowerQuery(){
      if ((this.queryLeadUserListParams.page_size + 5)<(this.totalRecords + 5)){
        this.inTheEnd = false;
        this.queryLeadUserListParams.page_size = this.queryLeadUserListParams.page_size +5
        this.queryUserList()
      }else {
        this.inTheEnd = true;
      }
    }
  },
  created() {

  },
  mounted() {
    this.getMenuListData();
    this.getFilterColumns();
    this.queryUserList();
  },
  onLoad(params) {
    this.queryLeadUserListParams.followStatus = params.status;
  },
  components: {
    Segmented,
    UniDataSelect,
    UniCollapse
  },
  watch: {
    'saveAssignUserParams.saleId':{
      handler(newVal, oldVal) {
        if (newVal){
          this.saveAssignUserDisabled=false
        }else {
          this.saveAssignUserDisabled=true
        }
      },
      immediate: true
    },
    // 'saveFollowRecordParams.status':{
    //   handler(newVal, oldVal) {
    //     if (newVal != null && newVal !== ''){
    //       this.saveFollowRecordDisabled=false
    //     }else {
    //       this.saveFollowRecordDisabled=true
    //     }
    //   },
    //   immediate: true
    // }
  }
};
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
