<template>
  <div class="ele-body">
    <el-card shadow="never" v-loading="loading">
      <search :levelList="levelList" @search="reload"></search>
      <!-- 数据表格 -->
      <ele-pro-table
        ref="table"
        :columns="columns"
        :datasource="datasource"
        cache-key="systemRoleTable"
        :pageSize="20"
      >
        <!-- 表头工具栏 -->
        <template v-slot:toolbar>
          <el-button
            size="small"
            type="primary"
            icon="el-icon-plus"
            class="ele-btn-icon"
            @click="openEdit('', 'add')"
          >新建</el-button>
        </template>

        <template v-slot:code="{ row }">
          <el-link type="primary" :underline="false" @click="openEdit(row, 'view')">{{ row.code }}</el-link>
        </template>
        <!-- 操作列 -->
        <template v-slot:action="{ row }">
          <el-link
            type="primary"
            :underline="false"
            @click="openEdit(row, 'edit')"
            v-if="row.demandStatus != 1"
          >修改</el-link>
          <el-popconfirm
            v-if="row.demandStatus != 1"
            class="ele-action"
            title="确定要删除此售后需求吗？"
            @confirm="handleRemove(row)"
          >
            <template v-slot:reference>
              <el-link type="danger" :underline="false" icon="el-icon-delete">删除</el-link>
            </template>
          </el-popconfirm>

          <el-dropdown
            @command="(command) => handleCommand(command, row)"
            v-if="row.demandStatus == 0"
          >
            <span class="el-dropdown-link">
              操作菜单
              <i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="handleRevoke">撤回</el-dropdown-item>
              <el-dropdown-item command="handleAudit">提交</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </ele-pro-table>
    </el-card>

    <!-- 新建或编辑弹窗 -->
    <AddDialog ref="addDialogRef" :dialogTitle="addDialogTitle" @refresh="reload" />
    <!-- 审核弹窗 -->
    <ele-modal
      :centered="true"
      :visible.sync="auditDialog"
      title="审核"
      :close-on-click-modal="false"
      width="25%"
      append-to-body
      @close="handleClose"
    >
      <el-form ref="form" :model="formData">
        <el-form-item
          prop="approvalResult"
          label="审核结果"
          :rules="{
            required: true,
            message: '请选择',
            trigger: 'change'
          }"
        >
          <el-select
            v-model="formData.approvalResult"
            placeholder="请选择"
            style="width: 100%"
            clearable
          >
            <el-option
              v-for="item in approvalResultOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          prop="rejectCause"
          label="审核意见"
          :rules="{
            required: formData.approvalResult == 0,
            message: '请输入',
            trigger: 'change'
          }"
        >
          <el-input v-model="formData.rejectCause" placeholder="请输入" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="footer">
        <el-button type="primary" @click="handleSubmit">确认</el-button>
        <el-button @click="handleClose">取消</el-button>
      </div>
    </ele-modal>
  </div>
</template>

<script>
import {
  getPageSalesDemand,
  deleteSalesDemand,
  auditSalesDemand,
  revokeSalesDemand
} from '@/api/salesServiceManagement/index.js';
import search from './components/searchTable.vue';
import AddDialog from './components/addDialog.vue';
import { getByCode } from '@/api/system/dictionary-data';
import dictMixins from '@/mixins/dictMixins';
export default {
  mixins: [dictMixins],
  components: {
    search,
    AddDialog
  },
  data() {
    return {
      // 表格列配置
      columns: [
        {
          columnKey: 'index',
          label: '序号',
          type: 'index',
          width: 55,
          align: 'center',
          showOverflowTooltip: true,
          fixed: 'left'
        },
        {
          slot: 'code',
          prop: 'code',
          label: '编码',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 110
        },
        {
          prop: 'contactCode',
          label: '客户编码',
          align: 'center',
          showOverflowTooltip: true
        },
        {
          prop: 'contactName',
          label: '客户名称',
          align: 'center',
          showOverflowTooltip: true
        },
        {
          slot: 'faultLevel',
          prop: 'faultLevel',
          label: '故障等级',
          align: 'center',
          showOverflowTooltip: true,
          formatter: (row) => {
            return this.levelData[row.faultLevel] || '';
          }
        },
        {
          prop: 'createUserName',
          label: '创建人',
          align: 'center',
          showOverflowTooltip: true
        },
        {
          prop: 'createTime',
          label: '创建时间',
          align: 'center',
          showOverflowTooltip: true,
          formatter: (_row, _column, cellValue) => {
            return this.$util.toDateString(cellValue);
          }
        },
        {
          prop: 'approvalUserName',
          label: '审核人',
          align: 'center',
          showOverflowTooltip: true
        },
        {
          prop: 'approvalTime',
          label: '审核时间',
          align: 'center',
          showOverflowTooltip: true,
          formatter: (_row, _column, cellValue) => {
            return this.$util.toDateString(cellValue);
          }
        },
        {
          prop: 'demandStatus',
          label: '状态',
          align: 'center',
          showOverflowTooltip: true,
          formatter: (_row, _column, cellValue) => {
            return cellValue == 0
              ? '待审核'
              : cellValue == 2
              ? '已拒绝'
              : cellValue == 1
              ? '已通过'
              : cellValue == 3
              ? '已撤回'
              : '';
          }
        },
        {
          columnKey: 'action',
          slot: 'action',
          label: '操作',
          align: 'center',
          width: 230,
          resizable: false,
          showOverflowTooltip: true
        }
      ],
      // 加载状态
      loading: false,
      infoData: {},
      repairInfoLogs: [],
      addDialogTitle: '新建售后需求',
      auditDialog: false,

      rowData: {},
      formData: {
        approvalResult: null,
        rejectCause: '',
        approvalUserId: '',
        approvalUserName: ''
      },
      approvalResultOptions: [
        { label: '驳回', value: 0 },
        { label: '同意', value: 1 }
      ],
      levelData: {},
      levelList: [],

    };
  },
  computed: {},
  created() {
    this.requestDict('报修来源');
    this.requestDict('报修状态');
    this.getLevelCode('fault_level');
  },
  methods: {
    /* 表格数据源 */
    datasource({ page, limit, where, order }) {
      return getPageSalesDemand({ pageNum: page, size: limit, ...where });
    },
    async changeEnable(row) {
      const res = await putRoles(row);
      if (res.code == 0) {
        this.$message({
          type: 'success',
          message: '修改成功',
          customClass: 'ele-message-border'
        });
        this.reload();
      }
    },
    //查询问题等级字典
    async getLevelCode(code) {
      const res = await getByCode(code);
      if (res?.code === '0') {
        let obj = {};
        let arr = [];
        res.data.map((el) => {
          arr.push({ label: Object.values(el)[0], value: Object.keys(el)[0] });
          obj = { ...obj, ...el };
        });
        this.levelList = arr;
        this.levelData = obj;
      }
    },
    /* 刷新表格 */
    reload(where) {
      this.$refs.table.reload({ page: 1, where });
    },

    openEdit(row, type) {
      this.$refs.addDialogRef.init(row, type);
    },

    handleRemove(row) {
      deleteSalesDemand([row.id]).then((res) => {
        this.$message.success('删除成功！');
        this.reload();
      });
    },
    async handleAudit(row) {
      this.auditDialog = true;
      this.rowData = row;
    },
    handleClose() {
      this.auditDialog = false;
    },
    async handleSubmit() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          const data = this.$store.state.user.info;

          let pdata = {
            id: this.rowData.id,
            approvalResult: this.formData.approvalResult,
            rejectCause: this.formData.rejectCause,
            approvalUserId: data.userId,
            approvalUserName: data.name
          };
          const res = await auditSalesDemand(pdata);
          if (res) {
            this.$message.success('审核成功！');
            this.auditDialog = false;
            this.reload();
          }
        }
      });
    },
    async handleRevoke(row) {
      const res = await revokeSalesDemand({ id: row.id });
      if (!res) return;
      this.$message.success('撤回成功！');
      this.reload();
    },
    handleCommand(command, row) {
      if (command === 'handleRevoke') {
        this.handleRevoke(row);
      }
      if (command === 'handleAudit') {
        this.handleAudit(row);
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.el-dropdown-link {
  cursor: pointer;
  color: var(--color-primary-5);
}

.el-icon-arrow-down {
  font-size: 12px;
}
</style>
