<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" v-show="showSearch" label-width="100px">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="供应商编码" prop="supplierCode">
            <el-input
              v-model="queryParams.supplierCode"
              placeholder="请输入供应商编码"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="供应商名称" prop="supplierName">
            <el-input
              v-model="queryParams.supplierName"
              placeholder="请输入供应商名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="供应商分类" prop="category">
            <el-select v-model="queryParams.category" placeholder="请选择供应商分类" clearable>
              <el-option
                v-for="dict in (dict.type.supplier_category || [])"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="所在区域" prop="area">
            <el-select v-model="queryParams.area" placeholder="请选择所在区域" clearable>
              <el-option
                v-for="dict in (dict.type.supplier_area || [])"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
              <el-option
                v-for="dict in (dict.type.supplier_status || [])"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="评分" prop="rating">
            <el-select v-model="queryParams.rating" placeholder="请选择评分" clearable>
              <el-option label="5星" :value="5" />
              <el-option label="4星" :value="4" />
              <el-option label="3星" :value="3" />
              <el-option label="2星" :value="2" />
              <el-option label="1星" :value="1" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="dateRange"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 100%"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <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-col>
      </el-row>
    </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="['resource: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="['resource: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="['resource:supplier:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="supplierList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="供应商编码" align="center" prop="supplierCode" :show-overflow-tooltip="true" min-width="120" />
      <el-table-column label="供应商名称" align="center" prop="supplierName" :show-overflow-tooltip="true" min-width="150" />
      <el-table-column label="统一社会信用代码" align="center" prop="creditCode" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="供应商分类" align="center" prop="category" width="120">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.supplier_category" :value="scope.row.category" />
        </template>
      </el-table-column>
      <el-table-column label="所在区域" align="center" prop="area" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.supplier_area" :value="scope.row.area" />
        </template>
      </el-table-column>
      <el-table-column label="联系人" align="center" prop="contactPerson" width="100" />
      <el-table-column label="联系电话" align="center" prop="contactPhone" width="120" />
      <el-table-column label="邮箱" align="center" prop="email" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.supplier_status" :value="scope.row.status || 'active'" />
        </template>
      </el-table-column>
      <el-table-column label="评分" align="center" prop="rating" width="150">
        <template slot-scope="scope">
          <el-rate v-model="scope.row.rating" disabled show-score :colors="['#99A9BF', '#F7BA2A', '#FF9900']" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="350" fixed="right" 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="['resource:supplier:edit']"
          >编辑</el-button>
          <el-dropdown>
            <span class="el-dropdown-link">
              状态<i class="el-icon-arrow-down el-icon--right" />
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                v-if="scope.row.status === 'inactive'"
                v-hasPermi="['resource:supplier:edit']"
                @click.native="handleActivate(scope.row)"
              >启用</el-dropdown-item>
              <el-dropdown-item
                v-if="scope.row.status === 'active'"
                v-hasPermi="['resource:supplier:edit']"
                @click.native="handleDeactivate(scope.row)"
              >停用</el-dropdown-item>
              <el-dropdown-item
                v-if="scope.row.status === 'active' || scope.row.status === 'inactive'"
                v-hasPermi="['resource:supplier:edit']"
                @click.native="handleBlacklist(scope.row)"
              >加入黑名单</el-dropdown-item>
              <el-dropdown-item
                v-if="scope.row.status === 'blacklisted'"
                v-hasPermi="['resource:supplier:edit']"
                @click.native="handleRemoveBlacklist(scope.row)"
              >解除黑名单</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-star-on"
            @click="handleRate(scope.row)"
            v-hasPermi="['resource:supplier:edit']"
          >评分</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document"
            @click="handleViewLicense(scope.row)"
            v-hasPermi="['resource:supplier:query']"
          >查看资质</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['resource: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="900px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="140px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="供应商编码" prop="supplierCode">
              <el-input v-model="form.supplierCode" placeholder="请输入供应商编码" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商名称" prop="supplierName">
              <el-input v-model="form.supplierName" placeholder="请输入供应商名称" maxlength="200" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="统一社会信用代码" prop="creditCode">
              <el-input v-model="form.creditCode" placeholder="请输入统一社会信用代码" maxlength="64" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商分类" prop="category">
              <el-select v-model="form.category" placeholder="请选择供应商分类" clearable style="width: 100%">
                <el-option
                  v-for="dict in (dict.type.supplier_category || [])"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="所在区域" prop="area">
              <el-select v-model="form.area" placeholder="请选择所在区域" clearable style="width: 100%">
                <el-option
                  v-for="dict in (dict.type.supplier_area || [])"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
                <el-option
                  v-for="dict in (dict.type.supplier_status || [])"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系人" prop="contactPerson">
              <el-input v-model="form.contactPerson" placeholder="请输入联系人" maxlength="64" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="form.contactPhone" placeholder="请输入联系电话" maxlength="20" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="100" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="评分" prop="rating">
              <el-rate v-model="form.rating" :max="5" :colors="['#99A9BF', '#F7BA2A', '#FF9900']" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="地址" prop="address">
              <el-input v-model="form.address" type="textarea" placeholder="请输入地址" maxlength="500" :rows="2" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" maxlength="500" :rows="3" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 评分对话框 -->
    <el-dialog title="供应商评分" :visible.sync="rateOpen" width="400px" append-to-body :close-on-click-modal="false">
      <el-form ref="rateForm" :model="rateForm" label-width="100px">
        <el-form-item label="评分">
          <el-rate v-model="rateForm.rating" :max="5" :colors="['#99A9BF', '#F7BA2A', '#FF9900']" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitRate">确 定</el-button>
        <el-button @click="rateOpen = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 资质管理弹窗 -->
    <supplier-license-dialog
      :visible.sync="licenseOpen"
      :supplier-id="currentSupplierId"
      :supplier-name="currentSupplierName"
      @success="handleLicenseSuccess"
    />
  </div>
</template>

<script>
import {
  listSupplier,
  getSupplier,
  addSupplier,
  updateSupplier,
  delSupplier,
  activateSupplier,
  deactivateSupplier,
  blacklistSupplier,
  rateSupplier
} from '@/api/resource/supplier'
import SupplierLicenseDialog from './components/SupplierLicenseDialog'

export default {
  name: 'ResourceSupplier',
  dicts: ['supplier_status', 'supplier_category', 'supplier_area'],
  components: {
    SupplierLicenseDialog
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      supplierCodes: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 供应商表格数据
      supplierList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 评分对话框
      rateOpen: false,
      // 资质管理弹窗
      licenseOpen: false,
      // 当前查看资质的供应商
      currentSupplierId: null,
      currentSupplierName: '',
      // 日期范围
      dateRange: [],
      // 表单参数
      form: {},
      // 评分表单
      rateForm: {},
      // 当前评分供应商
      currentSupplier: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        supplierCode: undefined,
        supplierName: undefined,
        category: undefined,
        area: undefined,
        status: undefined,
        rating: undefined
      },
      // 表单校验
      rules: {
        supplierCode: [
          { required: true, message: '供应商编码不能为空', trigger: 'blur' },
          { max: 50, message: '供应商编码长度不能超过50个字符', trigger: 'blur' }
        ],
        supplierName: [
          { required: true, message: '供应商名称不能为空', trigger: 'blur' },
          { max: 200, message: '供应商名称长度不能超过200个字符', trigger: 'blur' }
        ],
        creditCode: [{ max: 64, message: '统一社会信用代码长度不能超过64个字符', trigger: 'blur' }],
        category: [{ max: 64, message: '供应商分类长度不能超过64个字符', trigger: 'blur' }],
        area: [{ max: 100, message: '所在区域长度不能超过100个字符', trigger: 'blur' }],
        contactPerson: [{ max: 64, message: '联系人长度不能超过64个字符', trigger: 'blur' }],
        contactPhone: [{ max: 20, message: '联系电话长度不能超过20个字符', trigger: 'blur' }],
        email: [
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] },
          { max: 100, message: '邮箱长度不能超过100个字符', trigger: 'blur' }
        ],
        address: [{ max: 500, message: '地址长度不能超过500个字符', trigger: 'blur' }],
        remark: [{ max: 500, message: '备注长度不能超过500个字符', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询供应商列表 */
    getList() {
      this.loading = true
      const params = { ...this.queryParams }
      this.addDateRange(params, this.dateRange, 'Time')
      listSupplier(params).then(response => {
        this.supplierList = response.rows || []
        this.total = response.total || 0
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        supplierCode: undefined,
        supplierName: undefined,
        creditCode: undefined,
        category: undefined,
        area: undefined,
        contactPerson: undefined,
        contactPhone: undefined,
        email: undefined,
        address: undefined,
        status: 'active',
        rating: 5,
        remark: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.supplierCodes = selection.map(item => item.supplierCode)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加供应商'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids[0]
      getSupplier(id).then(response => {
        const data = response.data || {}
        this.form = {
          id: data.id,
          supplierCode: data.supplierCode,
          supplierName: data.supplierName,
          creditCode: data.creditCode,
          category: data.category,
          area: data.area,
          contactPerson: data.contactPerson,
          contactPhone: data.contactPhone,
          email: data.email,
          address: data.address,
          status: data.status || 'active',
          rating: data.rating || 5,
          remark: data.remark
        }
        this.open = true
        this.title = '编辑供应商'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateSupplier(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addSupplier(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      let ids = this.ids;
      let curNames = [];
      if (row) {
        ids = row.id || this.ids;
        curNames.push(row.supplierCode)
      } else if (this.supplierCodes.length > 0) {
        curNames.push(...this.supplierCodes)
      }
      const quotedNames = curNames.map(item => `“${item}”`);
      const resNames = quotedNames.join('、');
      this.$modal.confirm('是否确认删除供应商编码为' + resNames + '的数据项？').then(() => {
        return delSupplier(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    /** 启用供应商 */
    handleActivate(row) {
      this.$modal.confirm('是否确认启用该供应商？').then(() => {
        return activateSupplier(row.id)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('启用成功')
      }).catch(() => {})
    },
    /** 停用供应商 */
    handleDeactivate(row) {
      this.$modal.confirm('停用后该供应商将不可用，是否确认停用？').then(() => {
        return deactivateSupplier(row.id)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('停用成功')
      }).catch(() => {})
    },
    /** 加入黑名单 */
    handleBlacklist(row) {
      this.$modal.confirm('加入黑名单后该供应商将无法参与采购报价，是否确认加入黑名单？').then(() => {
        return blacklistSupplier(row.id)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('加入黑名单成功')
      }).catch(() => {})
    },
    /** 解除黑名单 */
    handleRemoveBlacklist(row) {
      this.$modal.confirm('解除黑名单后该供应商将可以参与采购报价，是否确认解除黑名单？').then(() => {
        return activateSupplier(row.id)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('解除黑名单成功')
      }).catch(() => {})
    },
    /** 评分按钮操作 */
    handleRate(row) {
      this.currentSupplier = row
      this.rateForm = {
        rating: row.rating || 5
      }
      this.rateOpen = true
    },
    /** 提交评分 */
    submitRate() {
      if (!this.rateForm.rating || this.rateForm.rating < 1 || this.rateForm.rating > 5) {
        this.$modal.msgError('请选择1-5星的评分')
        return
      }
      rateSupplier(this.currentSupplier.id, this.rateForm.rating).then(response => {
        this.$modal.msgSuccess('评分成功')
        this.rateOpen = false
        this.getList()
      })
    },
    /** 查看资质 */
    handleViewLicense(row) {
      this.currentSupplierId = row.id
      this.currentSupplierName = row.supplierName
      this.licenseOpen = true
    },
    /** 资质操作成功回调 */
    handleLicenseSuccess() {
      // 资质操作成功后可以刷新列表或执行其他操作
      // 这里暂时不需要刷新供应商列表
    }
  }
}
</script>

<style scoped>
.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
  margin: 0 6px;
}
</style>