<template>
  <div class="ele-body">
    <el-card shadow="never" v-loading="loading">
      <work-search
        class="seep-search"
        ref="workSearch"
        :levelList="levelList"
        @search="reload"
      ></work-search>
      <el-tabs v-model="orderStatus" type="card" @tab-click="handleClick">
        <el-tab-pane label="全部" name="all"></el-tab-pane>
        <el-tab-pane label="待执行" name="0"></el-tab-pane>
        <el-tab-pane label="执行中" name="1"></el-tab-pane>
        <el-tab-pane label="待验收" name="3"></el-tab-pane>
        <el-tab-pane label="已完成" name="5"></el-tab-pane>
      </el-tabs>
      <!-- 数据表格 -->
      <ele-pro-table
        ref="table"
        :columns="columns"
        :datasource="datasource"
        cache-key="systemRoleTable"
        :pageSize="20"
      >
        <!-- 表头工具栏 -->
        <template v-slot:toolbar></template>
        <template v-slot:code="{ row }">
          <el-link
            type="primary"
            :underline="false"
            @click="declarationForm(row, 'view')"
            >{{ row.code }}</el-link
          >
        </template>
        <!-- 操作列 -->
        <template v-slot:action="{ row }">
          <el-link
            type="primary"
            :underline="false"
            @click="declarationForm(row, 'edit')"
            v-if="
              (row.orderStatus == 1 || row.orderStatus == 6) &&
              $hasPermission('eom:aftersalesworkorder:update')
            "
            >修改</el-link
          >
          <el-link
            type="primary"
            :underline="false"
            @click="declarationForm(row, 'report')"
            v-if="
              (row.orderStatus == 1 || row.orderStatus == 6) &&
              $hasPermission('eom:aftersalesworkorder:reportWorking')
            "
            >报工</el-link
          >
          <el-link
            type="primary"
            v-if="
              row.orderStatus == 0 &&
              $hasPermission('eom:aftersalesworkorder:receive')
            "
            :underline="false"
            @click="handleCommand('handleReceive', row)"
            >接收</el-link
          >
          <el-link
            type="primary"
            v-if="
              (row.orderStatus == 0 || row.orderStatus == 1) &&
              $hasPermission('eom:aftersalesworkorder:reassignment')
            "
            :underline="false"
            @click="handleCommand('toRedeploy', row)"
            >转派</el-link
          >
          <el-link
            type="primary"
            v-if="
              (row.orderStatus == 1 || row.orderStatus == 2) &&
              $hasPermission('eom:sparepartsapply:save')
            "
            :underline="false"
            @click="handleCommand('addSpareItems', row)"
            >申请配件</el-link
          >
          <el-link
            type="primary"
            v-if="
              acceptShow(row) &&
              $hasPermission('eom:aftersalesworkorder:checkAndAccept')
            "
            :underline="false"
            @click="handleCommand('checkAndAccept', row)"
            >验收</el-link
          >
          <!--    v-if="row.orderStatus == 4" -->
          <el-link
            type="primary"
            v-if="
              evaluateShow(row) &&
              $hasPermission('eom:aftersalesworkorder:comment')
            "
            :underline="false"
            @click="handleCommand('evaluate', row)"
            >评价</el-link
          >
        </template>
      </ele-pro-table>
    </el-card>
    <!-- 详情 -->
    <detailDialog ref="detailDialogRef"></detailDialog>
    <!-- 备品备件 -->
    <applyForSpare @reload="reload" ref="edit" />
    <!-- 报工 -->
    <declarationDialog
      ref="declarationDialogRef"
      @reload="reload"
    ></declarationDialog>
    <!-- 转派 -->
    <redeployOther ref="redeployOtherRef" @reload="reload" />
    <ele-modal
      custom-class="ele-dialog-form long-dialog-form"
      :visible.sync="visibleCheckAndAccept"
      title="验收"
      :close-on-click-modal="false"
      width="500px"
      append-to-body
      :maxable="true"
    >
      <div>
        <el-form
          ref="form"
          :model="form"
          label-width="100px"
          class="create-form"
        >
          <el-form-item label="验收人" prop="accepterUserId">
            <el-select
              v-model="form.accepterUserId"
              size="small"
              style="width: 100%"
            >
              <el-option
                :value="item.id"
                :label="item.contactName"
                v-for="(item, index) in contactInfoVOS"
                @click.native="accepterUserChange(item)"
                :key="index"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="验收意见" prop="accepterRemark">
            <el-input
              placeholder="请输入内容"
              v-model="form.accepterRemark"
              type="textarea"
            ></el-input>
          </el-form-item>
          <el-form-item label="附件" prop="accepterAttachments">
            <fileMain v-model="form.accepterAttachments"></fileMain>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="footer">
        <el-button type="primary" @click="checkAndAccept(1)">通过</el-button>
        <el-button type="primary" @click="checkAndAccept(0)">不通过</el-button>
        <el-button @click="visibleCheckAndAccept = false">取消</el-button>
      </div>
    </ele-modal>
    <addDialog ref="addDialogRef" @success="reload"></addDialog>
  </div>
</template>

<script>
  // import fileMain from '@/components/addDoc/index.vue';
  import workSearch from './components/work-search.vue';
  import detailDialog from './components/detailDialog.vue';
  import applyForSpare from '../components/applyForSpare.vue';
  import declarationDialog from './components/declarationDialog.vue';
  import redeployOther from './components/redeployOther2.vue';
  import addDialog from '@/views/salesServiceManagement/evaluate/components/addDialog.vue';

  import {
    getSalesWorkOrder,
    deleteSalesWorkOrder,
    receiveSalesWorkOrder,
    checkAndAccept,
    getSalesWorkOrderById,
    checkByWorkId,
    afterSalesEvaluation
  } from '@/api/salesServiceManagement/index';
  import { getByCode } from '@/api/system/dictionary-data';
  import dictMixins from '@/mixins/dictMixins';
  export default {
    mixins: [dictMixins],
    components: {
      workSearch,
      detailDialog,
      applyForSpare,
      declarationDialog,
      redeployOther,
      addDialog,
      // fileMain
    },
    data() {
      return {
        visibleCheckAndAccept: false,
        form: {
          accepterUserId: '',
          accepterUserName: '',
          accepterRemark: ''
        },
        contactInfoVOS: [],
        workOrderStatus: [
          // { code: 0, label: '待接收' },
          { code: 0, label: '待执行' },
          { code: 1, label: '已接收' },
          { code: 2, label: '执行中' },
          { code: 3, label: '待验收' },
          { code: 4, label: '待评价' },
          { code: 5, label: '已完成' },
          { code: 6, label: '验收不通过' }
        ],
        resultStatus: [
          { code: 5, label: '未修复' },
          { code: 4, label: '已修复' }
        ],
        // 表格列配置
        columns: [
          {
            columnKey: 'index',
            label: '序号',
            type: 'index',
            width: 55,
            align: 'center',
            showOverflowTooltip: true,
            fixed: 'left'
          },
          {
            prop: 'code',
            slot: 'code',
            label: '工单编号',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 150
          },
          {
            prop: 'planCode',
            label: '计划单号',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110
          },
          {
            prop: 'planName',
            label: '计划名称',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110
          },
          {
            prop: 'executeUserName',
            label: '报工人',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110
          },
          {
            prop: 'accepterUserName',
            label: '验收人',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110
          },
          {
            slot: 'faultLevel',
            prop: 'faultLevel',
            label: '故障等级',
            align: 'center',
            showOverflowTooltip: true,
            formatter: (row) => {
              return this.levelData[row.faultLevel] || '';
            }
          },
          {
            prop: 'contactName',
            label: '客户名称',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110
          },
          {
            prop: 'categoryName',
            label: '设备名称',
            align: 'center',
            minWidth: 110,
            showOverflowTooltip: true,
            formatter: (row) => {
              if (!row.deviceDetails) return '';
              let str = '';
              row.deviceDetails.map((el, idx) => {
                if (idx + 1 == row.deviceDetails.length) {
                  str += el.categoryName;
                } else {
                  str = str + '' + el.categoryName + ',';
                }
              });
              return str;
            }
          },
          {
            prop: 'accepterTime',
            label: '验收时间',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110
          },
          {
            prop: 'acceptTime',
            label: '开始时间',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110
          },
          {
            prop: 'finishTime',
            label: '结束时间',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110
          },
          {
            prop: 'planFinishTime',
            label: '计划完成时间',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110
          },
          {
            prop: 'totalCost',
            label: '费用( 元 )',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110
          },
          {
            columnKey: 'inFactDuration',
            label: '工时',
            align: 'center',
            resizable: false,
            showOverflowTooltip: true,
            minWidth: 120,
            formatter: (row) => {
              if (row.inFactDuration || row.inFactDuration == 0) {
                let str = ((row.inFactDuration - 0) / 60).toFixed(1);
                return str + '  小时';
              }
            }
          },
          {
            prop: 'orderStatus',
            label: '状态',
            align: 'center',
            showOverflowTooltip: true,
            formatter: (row) => {
              return this.workOrderStatus.find(
                (item) => item.code == row.orderStatus
              )?.label;
            }
          },

          {
            columnKey: 'action',
            label: '操作',
            width: 240,
            align: 'center',
            resizable: false,
            slot: 'action',
            showOverflowTooltip: true
          }
        ],
        // 加载状态
        loading: false,
        row: {},
        levelData: {},
        levelList: [],
        orderStatus: 'all'
      };
    },

    computed: {
      // 评价
      evaluateShow() {
        return (row) => {
          return row.orderStatus == 4;
        };
      },
      // 验收
      acceptShow() {
        return (row) => {
          return row.orderStatus == 3 || row.orderStatus == 6;
        };
      }
    },
    created() {
      this.getLevelCode('fault_level');
    },
    methods: {
      handleClick(e) {
        let where = this.$refs.workSearch.$refs.seekPage.defaultWhere || {};
        this.reload(where);
      },
      //查询问题等级字典
      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;
        }
      },
      /* 表格数据源 */
      datasource({ page, limit, where, order }) {
        return getSalesWorkOrder({ pageNum: page, size: limit, ...where });
      },
      /* 刷新表格 */
      reload(where) {
        // 判断如果是选择的全部 不用传参
        if (this.orderStatus == 'all') {
          // where = where ? delete where.orderStatus : '';
          if (where) {
            delete where.orderStatus;
          }
          return this.$refs.table.reload({ page: 1, where });
        }
        // 不是的话 赋值工单状态
        if (!where) {
          where = { orderStatus: this.orderStatus };
        } else {
          where.orderStatus = this.orderStatus;
        }
        this.$refs.table.reload({ page: 1, where });
      },
      async cancel(row) {
        const res = await deleteSalesWorkOrder([row.id]);
        if (res) {
          this.$message.success('删除成功');
          this.reload();
        }
      },
      async addSpareItems(row) {
        let data = await getSalesWorkOrderById(row.id);
        let dataP = {
          receivingDeptName: data.executeGroupName,
          receivingDeptId: data.executeGroupId,
          recipientName: data.executeUserName,
          recipientId: data.executeUserId,
          name: data.name,
          receptionUserId: data.receptionUserId,
          id: data.id,
          userId: data.executeUserId,
          userName: data.executeUserName,
          details: data.costListVOS.filter((item) => {
            if (item.typeId == 2 && item.isApply != 1) {
              item.totalPrice = item.settlementPrice;
              item.categoryCode = item.code;
              item.categoryName = item.name;

              return item;
            }
          })
        };
        this.$refs.edit.open(JSON.parse(JSON.stringify(dataP)), 'work');
      },
      //接收
      async handleReceive(row) {
        const res = await receiveSalesWorkOrder(row);
        if (!res) return;
        this.$message.success('操作成功');
        this.reload();
      },
      //验收
      async checkAndAccept(accepterStatus) {
        if (!this.form.accepterUserId) {
          this.$message.warning('请选择验收人！');
          return;
        }
        const res = await checkAndAccept({
          id: this.row.id,
          ...this.form,
          accepterStatus
        });
        if (!res) return;
        this.$message.success('操作成功');
        this.visibleCheckAndAccept = false;
        this.reload();
      },
      accepterUserChange(item) {
        this.form.accepterUserName = item.contactName;
      },

      // 转派
      async toRedeploy(row) {
        this.$refs.redeployOtherRef.open(row, 'transfer');
      },
      //报工
      async declarationForm(row, type) {
        if (type !== 'view') {
          let flag = await this.permission(row);
          if (!flag) return;
        }
        this.$refs.declarationDialogRef.open(row, type);
      },
      // 校验
      async permission(row, command) {
        // 点评论/验收的话不走这个方法
        if (command == 'evaluate' || command == 'checkAndAccept') {
          return true;
        }
        try {
          await checkByWorkId(row.id);
          return true;
        } catch {
          return false;
        }
      },
      goDetail(row) {
        this.$refs.declarationDialogRef.open(row, 'view');
      },
      async handleCommand(command, row) {
        let flag = await this.permission(row, command);
        if (!flag) return;
        if (command === 'addSpareItems') {
          this.addSpareItems(row);
        }
        if (command === 'handleReceive') {
          this.handleReceive(row);
        }
        if (command === 'toRedeploy') {
          this.toRedeploy(row);
        }
        if (command == 'evaluate') {
          try {
            await afterSalesEvaluation(row.id);
            this.$refs.addDialogRef.open(row, 'add');
          } catch (err) {}
        }
        if (command == 'checkAndAccept') {
          try {
            await afterSalesEvaluation(row.id);
            this.visibleCheckAndAccept = true;
            this.form = {
              accepterUserId: '',
              accepterUserName: '',
              accepterRemark: ''
            };
            const { afterSalesDemandVO } = await getSalesWorkOrderById(row.id);
            this.contactInfoVOS = afterSalesDemandVO.contactInfoVOS || [];
            this.row = row;
          } catch (err) {}
        }
      }
    }
  };
</script>

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

  .el-icon-arrow-down {
    font-size: 12px;
  }

  ::v-deep .seep-search {
    .el-input__inner {
      padding: 0 5px 0 10px;
    }
  }
</style>
