<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="supplierName">
        <el-input
          v-model="queryParams.supplierName"
          placeholder="请输入供应商名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="地址" prop="supplierAddress">
        <el-input
          v-model="queryParams.supplierAddress"
          placeholder="请输入供应商地址"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系人" prop="supplierContact">
        <el-input
          v-model="queryParams.supplierContact"
          placeholder="请输入供应商联系人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系方式" prop="supplierContactNum">
        <el-input
          v-model="queryParams.supplierContactNum"
          placeholder="请输入供应商联系方式"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <div class="el-form-item" v-hasPermi="['business:supplier:usermanager']">
          <el-form-item label="管理人" prop="supplierManagers">
              <el-input
                v-model="queryParams.supplierManagers"
                placeholder="姓名间用英文逗号隔开"
                clearable
                @keyup.enter.native="handleQuery"
              />
          </el-form-item>
      </div>
      
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:supplier:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:supplier:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:supplier:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['business:supplier:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="supplierList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="65" align="center" />
      <!-- <el-table-column label="供应商Id" align="center" prop="supplierId" v-if="true"/> -->
      <el-table-column label="供应商名称" align="center" prop="supplierName" />
      <el-table-column label="供应商地址" align="center" prop="supplierAddress" />
      <el-table-column label="供应商联系人" align="center" prop="supplierContact" />
      <el-table-column label="供应商联系方式" align="center" prop="supplierContactNum" />
      <!--<el-table-column label="认领人" align="center" /> -->
      <el-table-column label="备注" align="center" prop="remark" /> 
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:supplier:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:supplier:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 添加或修改供应商信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="160px">
        <el-form-item label="供应商名称" prop="supplierName">
          <el-input v-model="form.supplierName" placeholder="请输入供应商名称" />
        </el-form-item>
        <el-form-item label="供应商地址" prop="supplierAddress">
          <el-input v-model="form.supplierAddress" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="供应商联系人" prop="supplierContact">
          <el-input v-model="form.supplierContact" placeholder="请输入供应商联系人" />
        </el-form-item>
        <el-form-item label="供应商联系方式" prop="supplierContactNum">
          <el-input v-model="form.supplierContactNum" placeholder="请输入供应商联系方式" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>

      <!-- 管理人员信息表格 -->
      <div ref="userManagerDiv" class="manager-table" v-hasPermi="['business:supplier:usermanager']">
        <h3>管理人员信息</h3>
        <el-table :data="filteredDockerUsers" border style="width: 100%">
          <el-table-column prop="userName" label="用户账号" width="100"></el-table-column>
          <el-table-column prop="nickName" label="用户昵称" width="100"></el-table-column>
             <el-table-column label="操作" width="100">
            <template slot-scope="scope">
              <el-button size="mini" type="text" @click="removeManager(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 用户选择器 -->
        <div class="user-selector">
          <h3>选择管理人员</h3>
          <el-select v-model="selectedUser" placeholder="请选择用户" @change="selectUser">
            <el-option
              v-for="user in users"
              :key="user.userId"
              :label="user.nickName"
              :value="user"
            >
          
          </el-option>
          </el-select>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSupplier, getSupplier, delSupplier, addSupplier, updateSupplier } from "@/api/business/supplier";
import { listAllUser,listUser, getUser, delUser, addUser, updateUser, resetUserPwd, changeUserStatus, deptTreeSelect } from "@/api/system/user";


import { getInfo} from "@/api/login";


export default {
  name: "Supplier",
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 供应商信息表格数据
      supplierList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        supplierName: undefined,
        supplierAddress: undefined,
        supplierContact: undefined,
        supplierContactNum: undefined,
        supplierManagers: undefined,
      },
      // 表单参数
      form: {
        supplierId: undefined,
        supplierName: undefined,
        supplierAddress: undefined,
        supplierContact: undefined,
        supplierContactNum: undefined,
        supplierManagers: undefined,
        remark: undefined,
        dockerUsers: []
      },
      // 表单校验
      rules: {
        supplierId: [
          { required: true, message: "供应商Id不能为空", trigger: "blur" }
        ],
        supplierName: [
          { required: true, message: "供应商名称不能为空", trigger: "blur" }
        ]
      },
      selectedUser: null, // 当前选中的用户
      users: [], // 用户列表
      currentUser: null, // 当前用户信息
      permissions: '' // 当前用户权限
    };
  },
  computed: {
    filteredDockerUsers() {
      return this.form.dockerUsers.length ? this.form.dockerUsers.filter(dockerUser => dockerUser.del === null): [];
    },
    //...mapState('user', ['permissions'])
  },
  async created() {
    
    try {
        const response = await getInfo();
        this.currentUser = response.data.user;
        this.permissions = response.data.permissions;

        console.log(response.data);

        // 在异步操作完成后再调用 getList()
        this.getList();
    } catch (error) {
        console.error('获取用户信息失败', error);
    }
  },
  methods: {
    /** 查询供应商信息列表 */
    getList() {
      this.loading = true;
 
      if (this.hasPermission("*:*:*") || this.hasPermission('business:supplier:usermanager')){
          this.queryParams.supplierManagers = '';
          //console.log("超级管理员");
      
      } else {
          this.queryParams.supplierManagers = this.currentUser.nickName;
          //console.log(this.currentUser.nickName + "  123");
      }

      listSupplier(this.queryParams).then(response => {
        this.supplierList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
       this.open = false;   
      this.reset();
  
    },
    // 表单重置
    reset() {
      this.form = {
        supplierId: undefined,
        supplierName: undefined,
        supplierAddress: undefined,
        supplierContact: undefined,
        supplierContactNum: undefined,
        supplierManagers: undefined,
        remark: undefined,
        dockerUsers: [],
        currentUser:undefined,
        permissions:''
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.supplierId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.fetchUsers();
      this.open = true;
      this.title = "添加供应商信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      //console.log(row);
      
      this.loading = true;
      this.reset();

      this.fetchUsers();

      const supplierId = row.supplierId || this.ids
      getSupplier(supplierId).then(response => {
        this.loading = false;
        this.form = response.data;
        //console.log(response.data);
        this.open = true;
        this.title = "修改供应商信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      console.log("submitForm");
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.supplierId != null) {
            console.log("updateSupplier");
            updateSupplier(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            console.log("addSupplier");
            this.setDefaultUserManager(); // 设置默认的管理人员
            console.log("addSupplier1");
            addSupplier(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const supplierIds = row.supplierId || this.ids;
      this.$modal.confirm('是否确认删除供应商信息编号为"' + supplierIds + '"的数据项？').then(() => {
        this.loading = true;
        return delSupplier(supplierIds);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/supplier/export', {
        ...this.queryParams
      }, `supplier_${new Date().getTime()}.xlsx`)
    },
   
    // 删除管理人员
    removeManager(index) {
      //console.log(this.form.dockerUsers);
      //this.form.dockerUsers.splice(index, 1);
      this.form.dockerUsers[index].del = 1;
      //console.log(this.form.dockerUsers);
    },
    // 获取用户列表
    fetchUsers() {
      if (this.hasPermission("*:*:*")||(this.hasPermission("system:user:list") && this.hasPermission("business:supplier:usermanager"))){
          listAllUser().then(response => {
          this.users = response.data;
          //console.log(response.data);
          });
      }
  
    },
    // 选择用户
    selectUser(user) {
      const isInArray = this.form.dockerUsers.some(obj => obj.userId === user.userId );
      if (isInArray==false) {
          this.form.dockerUsers.push({
            userId: user.userId,
            userName: user.userName,
            nickName: user.nickName,
            del: null
          });
      }
      this.selectedUser = null; // 清空选中用户
    },
    hasPermission(permission) {
      return this.permissions.includes(permission);
    },

    setDefaultUserManager(){
      console.log("setDefaultUserManager");
      const div = this.$refs.userManagerDiv;
      console.log("setDefaultUserManager1");
      if (div) { //div 不可见时，设定供应商的管理人员为当前用户
        console.log("has div");
        if (div.style.display !== 'none'){
            this.form.dockerUsers.push({
            userId: this.currentUser.userId,
            userName: this.currentUser.userName,
            nickName: this.currentUser.nickName,
            del: null
            });
            console.log("userManagerDiv 不可见");
        }else{
          console.log("userManagerDiv 可见");
        }
        
      }
  }
  },
  
};
</script>
