<template>
  <ele-modal
    custom-class="ele-dialog-form long-dialog-form"
    :centered="true"
    :visible.sync="addRepairNotesDialog"
    :title="title"
    :close-on-click-modal="false"
    width="85%"
    :maxable="true"
    append-to-body
    @close="handleClose"
  >
    <div class="switch" v-if="type == 'view'">
      <div class="switch_left">
        <ul>
          <li
            v-for="item in tabOptions"
            :key="item.key"
            :class="{ active: activeComp == item.key }"
            @click="handleTag(item.key)"
          >
            {{ item.name }}
          </li>
        </ul>
      </div>
    </div>
    <el-form
      ref="accessoryFormRef"
      :model="form"
      label-width="100px"
      v-show="activeComp === 'main'"
    >
      <headerTitle title="基本信息" style="margin-top: 15px"></headerTitle>
      <el-row>
        <el-col :span="6">
          <el-form-item label="编码:" prop="code">
            <el-input v-model="form.code" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item
            label="工单名称:"
            prop="name"
            :rules="{
              required: true,
              message: '请选择工单',
              trigger: 'change'
            }"
          >
            <el-input
              v-model="form.name"
              :disabled="type == 'view'"
              @click.native="handHead"
              placeholder="请选择"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item
            label="领用部门"
            prop="receivingDeptId"
            :rules="{
              required: true,
              message: '请输入领用部门',
              trigger: 'change'
            }"
          >
            <el-select
              style="width: 100%"
              v-model="form.receivingDeptId"
              disabled
              placeholder="请选择"
            >
              <el-option
                v-for="item in loginChangeGroupVOList"
                :key="item.groupId"
                :label="item.groupName"
                :value="item.groupId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item
            label="领用人"
            prop="recipientName"
            :rules="{
              required: true,
              message: '请输入领用人',
              trigger: 'change'
            }"
          >
            <el-input v-model="form.recipientName" disabled />
            <!-- <el-select style="width: 100%;" v-model="form.recipientName" disabled placeholder="请选择">
              <el-option
                v-for="item in loginChangeRoleVOList"
                :key="item.roleId"
                :label="item.roleName"
                :value="item.roleId"
              ></el-option>
            </el-select> -->
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="使用时间:" prop="usageTime">
            <el-date-picker
              style="width: 100%"
              v-model="form.usageTime"
              type="date"
              placeholder="选择"
              value-format="yyyy-MM-dd HH:mm:ss"
              :disabled="type == 'view'"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item
            label="使用部门"
            prop="useDeptId"
            :rules="{
              required: true,
              message: '请选择部门',
              trigger: 'change'
            }"
          >
            <deptSelect
              v-model="form.useDeptId"
              :disabled="type == 'view'"
              @changeGroup="searchDeptNodeClick"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item
            label="使用人"
            prop="userId"
            :rules="{
              required: true,
              message: '请选择使用人',
              trigger: 'change'
            }"
          >
            <el-select
              :disabled="type == 'view'"
              v-model="form.userId"
              size="small"
              style="width: 100%"
              filterable
              @change="changeUser"
            >
              <el-option
                v-for="item in executorList"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="用途:">
            <el-input
              :disabled="type == 'view'"
              v-model="form.purpose"
              type="textarea"
              :rows="2"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 配件信息 -->
      <spareInfo
        ref="spareInfoRef"
        :types="type"
        :detailList="detailList"
        v-if="addRepairNotesDialog"
      />
    </el-form>

    <bpmDetail
      v-if="activeComp === 'bpm' && form.processInstanceId"
      :id="form.processInstanceId"
    ></bpmDetail>

    <out-bound-details
      v-if="activeComp === 'store' && form.approvalStatus == 2"
      ref="innerBoundDetailsRef"
    ></out-bound-details>

    <workOrderList ref="workOrderListRef" @changeSelect="changeSelect" />
    <div slot="footer" class="footer">
      <el-button v-if="type != 'view'" type="primary" @click="save"
        >保存</el-button
      >
      <el-button @click="handleClose">取消</el-button>
    </div>
  </ele-modal>
</template>

<script>
  import bpmDetail from '@/views/bpm/processInstance/detail.vue';
  import outBoundDetails from '@/BIZComponents/outdetails.vue';
  import deptSelect from '@/components/CommomSelect/dept-select.vue';
  import workOrderList from './workOrderList.vue';
  import spareInfo from './spareInfo.vue';
  import { getUserPage } from '@/api/system/organization';
  import {
    accessorySave,
    accessoryUpdate
  } from '@/api/salesServiceManagement/index';
  import { getCurrentUser } from '@/utils/token-util';

  export default {
    data() {
      return {
        title: '新增',
        addRepairNotesDialog: false,
        type: 'add',
        form: {},
        loginChangeRoleVOList: [],
        executorList: [], // 执行人列表
        detailList: [],
        activeComp: 'main',
        tabOptions: [
          { key: 'main', name: '发货单详情' },
          { key: 'bpm', name: '流程详情' },
          { key: 'store', name: '出库单详情' }
        ]
      };
    },
    components: {
      workOrderList,
      spareInfo,
      deptSelect,
      bpmDetail,
      outBoundDetails
    },
    computed: {
      // 部门下拉
      loginChangeGroupVOList() {
        return this.$store.state.user?.info?.loginChangeGroupVOList;
      }
    },
    methods: {
      init(row, type) {
        // let currentUser = JSON.parse(sessionStorage['currentUser']);
        let currentUser = getCurrentUser();
        this.form.receivingDeptId = currentUser.currentGroupId; // 部门id
        this.roleVOListData();
        this.addRepairNotesDialog = true;
        this.type = type;
        this.title = type == 'add' ? '新增' : type == 'view' ? '详情' : '修改';
        if (row?.id) {
          this.getDetail(row);
        } else {
          this.form.recipientId = currentUser.currentRoleId; // 领用人Id
          // 下拉数据 name 赋值
          this.echoData();
        }
      },
      async getDetail(data) {
        const row = JSON.parse(JSON.stringify(data));
        const params = { groupId: row.useDeptId };
        this.getUserList(params);
        this.form.approvalStatus = row.approvalStatus;
        this.$set(this.form, 'code', row.code);
        this.$set(this.form, 'name', row.name);
        this.$set(this.form, 'receivingDeptId', row.receivingDeptId);
        this.$set(this.form, 'recipientId', row.recipientId);
        this.$set(this.form, 'usageTime', row.usageTime);
        this.$set(this.form, 'useDeptId', row.useDeptId);
        this.$set(this.form, 'userId', row.userId);
        this.$set(this.form, 'purpose', row.purpose);
        this.form.id = row.id;
        this.$set(this.form, 'recipientName', row.recipientName);
        this.form.receivingDeptName = row.receivingDeptName;
        this.form.useDeptName = row.useDeptName;
        this.form.userName = row.userName;
        this.form.repairId = row.repairId;
        this.detailList = row.details;
        this.form.docNo = row.docNo;
        this.form.orderCode = row.orderCode;
        this.form.processInstanceId = row.processInstanceId;
        console.log(this.form,'this.form ++++++')
      },
      handleTag(val) {
        this.activeComp = val;  
        if (val == 'store') {
          this.$nextTick(() => {
            console.log(this.form.orderCode,'this.form.orderCode ===')
            this.$refs.innerBoundDetailsRef._getInfo(this.form.code);
          });
        }
      },
      // 领用部门/领用人 name 赋值
      echoData() {
        const depObj = this.loginChangeGroupVOList.find(
          (item) => item.groupId === this.form.receivingDeptId
        );
        const roleObj = this.loginChangeRoleVOList.find(
          (item) => item.roleId === this.form.recipientId
        );
        this.form.receivingDeptName = depObj.groupName;
        this.$set(this.form, 'recipientName', roleObj.roleName);
      },
      // 选择工单
      handHead() {
        if (this.type != 'view') {
          this.$refs.workOrderListRef.open();
        }
      },
      // 确认选择工单
      changeSelect(row) {
        this.$set(this.form, 'name', row.name);
        this.form.repairId = row.id;
      },
      // 角色下拉
      roleVOListData() {
        let arr = this.loginChangeGroupVOList.find((item) => {
          return item.groupId == this.form.receivingDeptId;
        })?.loginChangeRoleVOList;
        this.loginChangeRoleVOList = arr;
      },
      //选择部门(搜索)
      searchDeptNodeClick(info, data) {
        if (info) {
          // 根据部门获取人员
          this.form.useDeptName = data.name;
          const params = { groupId: info };
          this.getUserList(params);
          this.$set(this.form, 'userName', '');
          this.$set(this.form, 'userId', '');
        } else {
          this.form.useDeptId = null;
        }
      },
      // 获取审核人列表、巡点检人员
      async getUserList(params) {
        try {
          let data = { pageNum: 1, size: -1 };
          // 如果传了参数就是获取巡点检人员数据
          if (params) {
            data = Object.assign(data, params);
          }
          const res = await getUserPage(data);
          if (params) {
            this.executorList = res.list;
          }
        } catch (error) {}
      },
      // 选择使用人
      changeUser(val) {
        this.executorList.map((item) => {
          if (item.id == val) {
            this.form.userName = item.name;
          }
        });
      },
      save() {
        let details = this.$refs.spareInfoRef.getSpareData() || [];
        if (details.length == 0) {
          this.$message.warning('请最少添加一条配件信息');
          return;
        }
        let obj = JSON.parse(JSON.stringify(this.form));
        delete obj.code;
        this.$refs.accessoryFormRef.validate(async (valid) => {
          if (valid) {
            let data = {
              ...obj,
              details
            };
            const requestname =
              this.title == '新增' ? accessorySave : accessoryUpdate;
            const res = await requestname(data);
            if (res) {
              this.$message.success('操作成功');
              this.handleClose();
              this.$emit('refresh');
            }
          }
        });
      },
      handleClose() {
        this.form = {};
        this.detailList = [];
        this.$refs.accessoryFormRef.resetFields();
        this.addRepairNotesDialog = false;
      }
    }
  };
</script>

<style></style>
