<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input v-model="listQuery.username" clearable class="filter-item" style="width: 200px;" placeholder="请输入管家名称" />
      <el-button v-permission="['GET /admin/sysbutler/butlerlist']" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row>
      <el-table-column align="center" label="管理员ID" prop="id" sortable />

      <el-table-column align="center" label="管理员名称" prop="userName" />
      <el-table-column align="center" label="管理员账号" prop="userAccount" />

      <!-- <el-table-column align="center" label="管理员头像" prop="avatar">
        <template slot-scope="scope">
          <img v-if="scope.row.avatar" :src="scope.row.avatar" width="40">
        </template>
      </el-table-column> -->

       <el-table-column align="center" label="管理员角色" prop="roleIds">
        <template slot-scope="scope">
          <el-tag v-for="roleId in scope.row.roleIds" :key="roleId" type="primary" style="margin-right: 20px;"> {{ formatRole(roleId) }} </el-tag>
        </template>
      </el-table-column>

      <!-- <el-table-column align="center" label="是否为管家" prop="butlerType">
        <template slot-scope="scope">
          {{scope.row.butlerType==1?'是':'否'}}
        </template>
      </el-table-column> -->
      <el-table-column align="center" label="负责城市" prop="citys">
        <template slot-scope="scope">
          <el-tag v-for="city in scope.row.citys" :key="city.id" type="primary" style="margin-right: 20px;"> {{ city.cityName }} </el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-permission="['POST /admin/sysbutler/updateBtCustomer']" type="primary" size="mini" @click="handleUpdate(scope.row)">设置管家客户</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <!-- 设置管家客户对话框 -->
    <el-dialog title="设置管家客户" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="left" label-width="100px" style="width: 600px; margin-left:50px;">

 
                <el-form-item label="管家客户" prop="customerClientId">
                    <el-select v-model="dataForm.customerClientId" style="width:400px" clearable filterable multiple >
                        <!-- multiple -->
                        <el-option v-for="item in jzmallCustomer" :key="item.id" :label="item.tel+item.customerName" :value="item.id" />
                    </el-select>
                </el-form-item>
          

       
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>


<script>

import { listAllCity } from '@/api/city'
import { list, pass, reject,shopList } from '@/api/disjoin'
import { listButler,getJzmallCustomer,getbtCustomer,updateBtCustomer, createAdmin, updateAdmin, deleteAdmin,readUserCitys } from '@/api/admin'
import { roleOptions } from '@/api/role'
import { uploadPath } from '@/api/storage'
import { getToken } from '@/utils/auth'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination

export default {
  name: 'Admin',
  components: { Pagination },
  data() {
    return {
      jzmallCustomer:[],
      userId:'',
      btCustomer:[],
      uploadPath,
      list: null,
      total: 0,
      citys:[],
      cityIds:[],
      shopIds:[],
      shopList:[],
      roleOptions: null,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        username: undefined,
        sort: 'create_time',
        order: 'desc'
      },
      dataForm: {
      customerClientId:[]
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {
       customerClientId: [{ required: true, message: '管家客户不能为空', trigger: 'change' }],

      },
      downloadLoading: false
    }
  },
  computed: {
    headers() {
      return {
        'X-JZ-Admin-Token': getToken()
      }
    }
  },
  created() {
     this.getList();
     this.getShopList();
     this.getJzmallCustomer();

    roleOptions()
      .then(response => {
        this.roleOptions = response.data.data.list
      })
      
    listAllCity().then(res=>{
      this.citys=res.data.data
    })
  },
  methods: {
      getShopList() {
      shopList().then(response => {
          this.shopList = response.data.data.list;
        })
        .catch(() => {
         
        })
    },
    formatRole(roleId) {
      for (let i = 0; i < this.roleOptions.length; i++) {
        if (roleId === this.roleOptions[i].value) {
          return this.roleOptions[i].label
        }
      }
      return ''
    },
    getJzmallCustomer(){
       getJzmallCustomer().then(response => {
          this.jzmallCustomer = response.data.data;
        })
        .catch(() => {
         
        })
    },
    getList() {
      this.listLoading = true
      listButler(this.listQuery)
        .then(response => {
          this.list = response.data.data.list
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        id: undefined,
        userName: undefined,
        userAccount: undefined,
        userPassword: undefined,
        avatar: undefined,
        roleIds: [],
        butlerType:0
      }
      this.cityIds=[];
      this.shopIds=[];
    },
    uploadAvatar: function(response) {
      this.dataForm.avatar = response.data.url
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
   
    handleUpdate(row) { 
      this.userId=row.id;
      getbtCustomer({userId:row.id}).then(res=>{
        this.dataForm.customerClientId=res.data.data.map(item=>{return item.id});
      })

      this.dialogFormVisible = true;
     
    },
    updateData() {
      console.info(this.cityIds) 
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          updateBtCustomer({userId:this.userId,customerClientId:this.dataForm.customerClientId})
            .then(() => {
           
               this.getList()
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '设置管家客户成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
        }
      })
    },
    handleDelete(row) {
      deleteAdmin(row)
        .then(response => {
          this.$notify.success({
            title: '成功',
            message: '删除管理员成功'
          })
          const index = this.list.indexOf(row)
          this.list.splice(index, 1)
        })
        .catch(response => {
          this.$notify.error({
            title: '失败',
            message: response.data.errmsg
          })
        })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['管理员ID', '管理员名称', '管理员头像']
        const filterVal = ['id', 'username', 'avatar']
        excel.export_json_to_excel2(
          tHeader,
          this.list,
          filterVal,
          '管理员信息'
        )
        this.downloadLoading = false
      })
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 145px;
  height: 145px;
  display: block;
}
  .el-table th.gutter{
          display: table-cell!important;
        }

        .fixed-width .el-button--mini{
          width:auto;
        }
</style>