<template>
  <div class="height_100">
    <el-container>
      <el-header>
        <!-- <div>
          <mySearch style="width: 500px" :SearchFields="searchFiled" @search="search" :searchValue="searchOption">
          </mySearch>
        </div>
        <div v-if="!choseClient">
          <el-button type="primary" size="small" @click="handleAdd()"> 新增 </el-button>
        </div> -->
        <el-form :inline="true">
          <el-form-item label="用户名">
            <el-input v-model="queryParams.name" size="small" placeholder="请输入用户名"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="" size="small" @click="getList">查询</el-button>
            <el-button type="primary" size="small" @click="handleAdd()" v-if="!choseClient">新增</el-button>
          </el-form-item>
        </el-form>
      </el-header>
      <el-main>
        <div class="height_100">
          <el-table v-loading="loading" :data="tableData" border header-row-class-name="custom-table-header">
            <el-table-column type="index" label="#" width="55" align="center">
              <template slot-scope="scope">
                <span>{{ (scope.$index + 1) + ((queryParams.current - 1) * queryParams.size) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="客户名称" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                <div>
                  <div v-if="!choseClient">{{ scope.row.name }}</div>
                  <div v-else>
                    <el-link type="primary" @click.native="getClient(scope.row)">{{ scope.row.name }}</el-link>
                  </div>

                </div>
              </template>
            </el-table-column>
            <!-- <template >
              <div> -->
                <el-table-column  v-show="!choseClient" prop="personnelName" label="客户对接人" align="center" show-overflow-tooltip></el-table-column>
                <el-table-column  v-show="!choseClient" prop="remark" label="备注" align="center" show-overflow-tooltip></el-table-column>
                <el-table-column  v-show="!choseClient" label="操作" align="center" width="150">
                  <template slot-scope="scope">
                    <el-dropdown split-button type="primary" size="small" @click="handleEdit(scope.row)">
                      <span>编辑</span> 
                        <el-dropdown-menu slot="dropdown" class="text-align_center">
                        <el-dropdown-item class="color-red" @click.native="handleDelete(scope.row)" divided>删除</el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                  </template>
                </el-table-column>
              <!-- </div>
            </template> -->
          </el-table>
        </div>

      </el-main>
      <el-footer>
        <div class="pagination">
          <el-pagination :current-page.sync="queryParams.current" :page-size="queryParams.size" :total="total"
            @current-change="handleCurrentChange" layout="total, prev, pager, next, jumper" background></el-pagination>
        </div>
      </el-footer>
    </el-container>

    <el-dialog :title="title" :visible.sync="visible" width="500px" :before-close="close" :append-to-body="true"  :close-on-click-modal="false">
      <el-form v-if="visible" :model="ruleForm" :rules="rules" ref="ruleForm" label-width="80px" label-position="left">
        <el-form-item label="客户名称" prop="name">
          <el-autocomplete style="width:100%" v-model="ruleForm.name" :fetch-suggestions="querySearch" @input="input"
            placeholder="请输入客户名称" :trigger-on-focus="false" @select="handleChange">
          </el-autocomplete>
        </el-form-item>
        <el-form-item label="对接人" prop="person">
          <el-select style="width:100%" v-model="ruleForm.personnelId" filterable placeholder="请选择">
            <el-option v-for="item in personnelList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="ruleForm.remark" placeholder="请输入备注" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="submit" :loading="btnLoading">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  components: {},
  props: {
    name: '',
    choseClient: false
  },
  data() {
    return {
      //弹窗显示标识
      visible: false,
      //加载
      loading: false,
      //按钮加载
      btnLoading: false,
      //人员列表
      personnelList: [],
      //总客户数
      total: 0,
      //客户列表数据
      tableData: [],
      //弹窗标题
      title: '',
      //分页信息
      queryParams: {
        size: 10,
        current: 1,
      },
      //表单信息
      ruleForm: {},
      //表单规则
      rules: {
        name: [{ required: true, message: '请输入客户名称', trigger: 'blur' },],
      },
      //租户列表
      tenantList: [],
      //检索字段
      searchFiled: [
        {
          label: '客户名称名称',
          value: 'name',
          type: 1,
          placeholder: '请输入客户名称'
        }
      ],
      //检索条件
      searchOption: {
        name: this.name
      },
    };
  },
  watch: {},
  computed: {},
  created() { },
  mounted() {
    this.getList()
    //获取客户信息（建议改成远程搜索，或者懒加载）
    this.getPersonnelList()
    //去除获取所有租户的方法以及相关信息
    this.getAllTenantList()
  },
  methods: {
    //检索
    search() {

    },
    //改为通过接口获取数据
    querySearch(queryString, cb) {
      var tenantList = this.tenantList;
      var results = (queryString ? tenantList.filter(this.createFilter(queryString)) : tenantList).map(item => {
        return {
          value: item.name,
          name: item.name,
          id: item.id
        }
      });
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (tenantList) => {
        return (tenantList.name.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    //获取所有租户信息
    getAllTenantList() {
      this.$api.getAllTenantList().then(response => {
        this.tenantList = response.data
      })
    },
    //输入事件
    input() {
      this.$set(this.ruleForm, 'tenantId', null)
    },
    //切换选择客户名称
    handleChange(row) {
      this.$set(this.ruleForm, 'tenantId', row.id)
      this.$set(this.ruleForm, 'name', row.name)
    },
    //打开新增客户弹窗
    handleAdd() {
      this.title = '新增客户'
      this.visible = true
      this.ruleForm = {}
    },
    //打开编辑客户弹窗
    handleEdit(row) {
      this.title = '编辑客户'
      this.visible = true
      this.ruleForm = { ...row }
    },
    //关闭弹窗
    close() {
      this.$refs.ruleForm.resetFields()
      this.visible = false
    },
    //获取所有人员信息（最好使用远程搜索）
    getPersonnelList() {
      this.$api.getPermissionPersonnelList().then((response) => {
        this.personnelList = response.data
      })
    },
    //获取客户信息
    getList() {
      this.loading = true
      this.$api.getAdminClientList(this.queryParams).then(response => {
        this.tableData = response.data.records
        this.total = response.data.total
        this.loading = false
      }).catch(error => {
        this.loading = false
      })
    },
    //分页
    handleCurrentChange(val) {
      this.queryParams.current = val;
      this.getList();
    },
    //提交信息
    submit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.btnLoading = true
          if (this.ruleForm.id) {
            this.$api.editAdminClient(this.ruleForm).then(response => {
              this.$message.success('编辑成功')
              this.btnLoading = false
              this.getList()
              this.close()
            }).catch(error => {
              this.btnLoading = false
            })
          } else {
            this.$api.addAdminClient(this.ruleForm).then(response => {
              this.$message.success('新增成功')
              this.btnLoading = false
              this.getList()
              this.close()
            }).catch(error => {
              this.btnLoading = false
            })
          }
        } else {
          // console.log('error submit!!');
          return false;
        }
      });
    },
    //删除客户
    handleDelete(row) {
      this.$confirm('确认删除本条数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        this.$api.deleteAdminClient({ id: row.id }).then(response => {
          this.$message.success('删除成功')
          this.loading = false
          this.getList()
        }).catch(error => {
          this.loading = false
        })
      })
    },
    //选择客户
    getClient(row) {
      this.$emit('getClient', row)
    },
  }
};
</script>
<style lang="scss" scoped></style>