<script setup>
import { reactive, ref,toRefs } from "vue";
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Search,MoreFilled } from '@element-plus/icons-vue'
import { customInterence ,businessCustomInterence , roadshowInterence} from '@/api/api.js'
import {locationOptions} from "@/views/custom_manage/custom/location"
import AddRenewal from './components/AddRenewal.vue'
import ModifySaller from './components/ModifySaller.vue'

const router = useRouter()

const tableColOpts = [
  {
      label:'商家名称',
      key:'BusinessName'
  },
  {
      label:'商家ID',
      key:'BusinessCode'
  },
  {
      label:'商家地址',
      key:'Address'
  },
  {
      label:'销售',
      key:'SellerName'
  },
  {
      label:'签约状态',
      key:'SigningStatus'
  },
  {
      label:'最新签约时间',
      key:'SigningTime',
      sort:true
  },
  {
      label:'到期时间',
      key:'ExpiredTime',
      sort:true
  },
  {
      label:'创建时间',
      key:'CreateTime',
      sort:true
  },
  {
      label:'用户上限',
      key:'UserMax',
      sort:true
  },
  
]
const signStatusOpts = [
    {
        label:'首次签约',
        val:1
    },
    {
        label:'续约中',
        val:2
    },
    {
        label:'已终止',
        val:3
    },
    {
        label:'待签约',
        val:4
    }
]

const locationProps = {
    multiple: true,
    value:'name',
    children:'city',
    label:'name'
}

/* 根据类型获取行业 */
const tradeArr = ref([])
function getIndustry() {
  customInterence.getindustry({
    Classify:'ficc'
  }).then(res => {
    if(res.Ret === 200) {
      tradeArr.value = res.Data.List || [];
    }
  })
}
getIndustry()


/* 获取销售 */
const salesArr = ref([])//销售
async function getSale() {
    const res = await roadshowInterence.getSellerList();
    if(res.Ret!==200) return 
    salesArr.value = res.Data.List||[]
    salesArr.value = salesArr.value.map(i=>{
        if(!i.AdminName){
            i.AdminName = i.GroupName
        }
        if(!i.AdminId){
            i.AdminId = i.GroupId
        }
        return i
    })
}
getSale()

const filterParams = reactive({
  search_txt: '',
  trade:'',
  sales: [],
  signStatus: '',
  provinceValue:'',
  cityValue:'',
  page:1,
  pageSize:20,
  sortParam:0,
  sortType:0,
  valueLocation: []
})
const tableData = ref([])
const isTableLoadding = ref(false)
const total = ref(0)
// 获取表格数据
function getBusinessList(){
    isTableLoadding.value = true
    businessCustomInterence.getBusinessList({
        Keyword:filterParams.search_txt,
        SellerIds:filterParams.sales.join(','),
        SigningStatus:Number(filterParams.signStatus),
        Province:filterParams.provinceValue,
        City:filterParams.cityValue,
        IndustryId:Number(filterParams.trade),
        PageSize:filterParams.pageSize,
        CurrentIndex:filterParams.page,
        SortParam:filterParams.sortParam,
        SortType:filterParams.sortType
    }).then(res=>{
        if(res.Ret!==200) return 

        tableData.value = res.Data.List
        total.value = res.Data.Paging.Totals
        isTableLoadding.value = false
    })
}
getBusinessList()

// 筛选项改变
function changeSelectOptions(option){
    if(option === 'location'){
        const provinceArr = []
        const cityArr = []
        filterParams.valueLocation.forEach(item=>{
                // 省
                provinceArr.push(item[0])
                // 市
                cityArr.push(item[1])
        })
        //provinceArr需要去重
        filterParams.provinceValue = [...new Set(provinceArr)].join(',')
        filterParams.cityValue = cityArr.join(',')
        filterParams.page = 1;
    }
    getBusinessList()
}

function handleCurrentChange(page){
  filterParams.page = page
  getBusinessList()
}

// 表格排序方式改变
function sortChangeHandle(params){
  const sortParamMap = {
      'SigningTime':1,//签约时间
      'ExpiredTime':2,//到期时间
      'CreateTime':3,//创建时间
      'UserMax':4,//用户上限
  }
  filterParams.sortParam = sortParamMap[params.prop]
  filterParams.sortType = params.order === 'ascending' ? 1 :params.order === 'descending' ? 2 : 0
  filterParams.page = 1
  getBusinessList()
}

// 去详情
function handleShowDetail(data){
  router.push({
      path:'/businessETADetail',
      query:{
          id:data.EtaBusinessId
      }
  })
}

// 前去编辑
function handleEdit(data){
    router.push({
        path:'/editETABusiness',
        query:{
            id:data.EtaBusinessId
        }
    })
}

 /* dialog */
const showRenewal = ref(false)//显示添加续约
const showModifySaller = ref(false)//显示修改销售
const modifyData = ref({})//当前操作的商家数据
// 显示添加续约
function handleShowRenewal(e){
    modifyData.value = e
    showRenewal.value=true
}
// 商家添加续约
function handleAddRenewal({signDate,expirationDate}){
    businessCustomInterence.addNewContract({
        EtaBusinessId:modifyData.value.EtaBusinessId,
        SigningTime:signDate,
        ExpiredTime:expirationDate
    }).then(res=>{
        if(res.Ret!==200) return 
        ElMessage.success('添加续约成功')
        showRenewal.value=false
        getBusinessList()
    })
}

// 商家修改销售
function handleModifySaller({saller,sallerName}){
    businessCustomInterence.changeBusinessSeller({
        EtaBusinessId:modifyData.value.EtaBusinessId,
        SellerId:saller,
        SellerName:sallerName
    }).then(res=>{
        if(res.Ret!==200) return 
        ElMessage.success('修改销售成功')
        showModifySaller.value = false
        getBusinessList()
    })
}

// 启用禁用商家
function changeBusinessStatus(data){
    businessCustomInterence.changeBusinessStatus({
        EtaBusinessId:data.EtaBusinessId
    }).then(res=>{
        if(res.Ret!==200) return 
        ElMessage.success(`${data.Enable?'禁用':'启用'}成功`)
        getBusinessList()
    })
}

// 操作栏 折叠起来的按钮
function itemclickHandle(type,data){
    if(type==='modifySale'){
        modifyData.value = data
        showModifySaller.value=true
    }else if (type==='disable'){
        changeBusinessStatus(data)
    }else if(type==='setAuth'){
        /* let {href} = this.$router.resolve({path:`/businessETAAuth`,query:{id:EtaBusinessId}});
          window.open(href,'_blank'); */
          router.push({
            path:'/businessETAAuth',
            query:{
                id:data.EtaBusinessId,
                name:data.BusinessName
            }
        })
    }
}

const {   
  search_txt,
  trade,
  sales,
  signStatus,
  page,
  pageSize,
  valueLocation } = toRefs(filterParams)
</script>
<template>
  <div class="business-ETA-list">
    <div class="top-filter-box">
      <div>
        <el-button type="primary" @click="router.push('/addETABusiness')"
          >新增</el-button
        >
        <el-input
          placeholder="商家名称/社会信用码/商家ID"
          v-model="search_txt"
          @input="changeSelectOptions('search')"
          clearable
          style="max-width: 500px; float: right"
          :prefix-icon="Search"
        >
        </el-input>
      </div>
    </div>
    <div class="table-wrap">
      <div class="select-wrap">
        <el-select
          v-model="trade"
          placeholder="请选择行业"
          clearable
          @change="changeSelectOptions('trade')"
        >
          <el-option
            v-for="item in tradeArr"
            :key="item.IndustryId"
            :label="item.IndustryName"
            :value="item.IndustryId"
          >
          </el-option>
        </el-select>
        <el-cascader
          ref="cascader"
          v-model="sales"
          :options="salesArr"
          :show-all-levels="false"
          :props="{
            expandTrigger: 'hover',
            children: 'Child',
            emitPath: false,
            label: 'AdminName',
            value: 'AdminId',
            multiple: true,
          }"
          collapse-tags
          filterable
          clearable
          placeholder="请选择销售"
          @change="changeSelectOptions('sales')"
        />
        <el-cascader
          v-model="valueLocation"
          collapse-tags
          :props="locationProps"
          clearable
          :options="locationOptions"
          @change="changeSelectOptions('location')"
          placeholder="请选择客户地址"
        />
        <el-select
          v-model="signStatus"
          placeholder="请选择签约状态"
          clearable
          @change="changeSelectOptions('signStatus')"
        >
          <el-option
            v-for="item in signStatusOpts"
            :key="item.val"
            :label="item.label"
            :value="item.val"
          >
          </el-option>
        </el-select>
      </div>
      <el-table
        ref="userTable"
        :data="tableData"
        v-loading="isTableLoadding"
        element-loading-text="数据加载中..."
        @sort-change="sortChangeHandle"
        border
      >
        <el-table-column
          v-for="item in tableColOpts"
          :key="item.key"
          :prop="item.key"
          :label="item.label"
          align="center"
          :sortable="item.sort"
        >
          <template #default="scope">
            <span v-if="item.key === 'SigningStatus'">
              {{ signStatusOpts[scope.row.SigningStatus - 1].label
              }}{{ !scope.row.Enable ? "（禁用）" : "" }}
            </span>
            <span
              v-else-if="item.key === 'BusinessName'"
              class="link"
              @click="handleShowDetail(scope.row)"
            >
              {{ scope.row.BusinessName }}
            </span>
            <span v-else>{{ scope.row[item.key] }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="100" align="center">
          <template #default="scope">
            <div class="table-opt-btns">
              <span @click="handleEdit(scope.row)">编辑</span>
              <span @click="handleShowRenewal(scope.row)">添加续约</span>
              <el-dropdown
                size="medium"
                placement="bottom-start"
                @command="itemclickHandle($event, scope.row)"
              >
                <span class="el-dropdown-link">
                  <el-icon><MoreFilled /></el-icon>
                </span>
                <template #dropdown>
                  <el-dropdown-menu >
                    <el-dropdown-item command="setAuth"
                      >权限设置</el-dropdown-item
                    >
                    <el-dropdown-item command="modifySale"
                      >修改销售</el-dropdown-item
                    >
                    <el-dropdown-item command="disable">{{
                      scope.row.Enable ? "禁用" : "启用"
                    }}</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div style="height:50px; margin-top: 20px">
        <el-pagination
          layout="total,prev,pager,next,jumper"
          background
          :current-page="page"
          @current-change="handleCurrentChange"
          :page-size="pageSize"
          :total="total"
          style="float:right"
        />
      </div>
    </div>

    <!-- 添加续约 -->
    <el-dialog
      title="添加续约"
      v-model="showRenewal"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      @closed="showRenewal = false"
      width="580px"
    >
      <AddRenewal @addRenewal="handleAddRenewal" @close="showRenewal = false" />
    </el-dialog>

    <!-- 修改销售 -->
    <el-dialog
      title="修改销售"
      v-model="showModifySaller"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      @closed="showRenewal = false"
      width="580px"
    >
      <ModifySaller
        :salesArr="salesArr"
        :data="modifyData"
        @modifySaller="handleModifySaller"
        @close="showModifySaller = false"
      />
    </el-dialog>
  </div>
</template>
<style lang="scss" scoped>
.top-filter-box{
    border: 1px solid #ECECEC;
    padding: 20px 30px;
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);
}
.table-wrap{
    margin-top: 30px;
    border: 1px solid #ECECEC;
    padding: 20px 30px;
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);
    .select-wrap{
        display: flex;
        gap:20px;
        align-items: center;
        margin-bottom: 20px;
        .el-select,.el-cascader{
            width:240px;
        }
    }
    .link{
        color:#4099ef;
        cursor: pointer;
        &:hover{
            text-decoration: underline;
        }
        
    }
}
.table-opt-btns{
    color:#4099ef;
    display:flex;
    align-content: center;
    justify-content: center;
    align-items: center;
    span{
        margin: 0 3px;
        cursor: pointer;
    }
}

.top-filter-box{
  :deep(.el-cascader__search-input) {
      min-width: 30px;
  }
} 


</style>
