<template>
  <ele-modal
    custom-class="ele-dialog-form long-dialog-form"
    :centered="true"
    :visible.sync="editRepairNotesDialog"
    :title="title"
    :close-on-click-modal="false"
    width="85%"
    :maxable="true"
    append-to-body
    @close="handleClose"
  >
    <el-form ref="recyleFormRef" :model="form" label-width="100px">
      <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="recycleDeptId"
            :rules="{
              required: true,
              message: '请输入回收部门',
              trigger: 'change'
            }"
          >
            <el-select style="width: 100%;" v-model="form.recycleDeptId" 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="recycleName"
          >
            <!-- <el-select style="width: 100%;" v-model="form.recycleId" disabled placeholder="请选择">
              <el-option
                v-for="item in loginChangeRoleVOList"
                :key="item.roleId"
                :label="item.roleName"
                :value="item.roleId"
              ></el-option>
            </el-select> -->
            <el-input v-model="form.recycleName" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item
            label="工单名称:"
            prop="orderWorkName"
            :rules="{
            required: true,
            message: '请选择工单',
            trigger: 'change'
          }"
          >
            <el-input
              v-model="form.orderWorkName"
              :disabled="type == 'view'"
              @click.native="handHead"
              placeholder="请选择"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="工单编码:">
            <el-input v-model="form.orderWorkCode" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="客户名称:" prop="code">
            <el-input v-model="form.contactName" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="客户编码:" prop="code">
            <el-input v-model="form.contactCode" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item
            label="设备名称"
            prop="demandDetailId"
            :rules="{
              required: true,
              message: '请选择设备名称',
              trigger: 'change'
            }"
          >
            <el-select
              popper-class="device_name"
              style="width: 100%;"
              :disabled="type == 'view'"
              v-model="form.demandDetailId"
              placeholder="请选择"
            >
              <el-option
                v-for="item in deviceList"
                :key="item.demandDetailId"
                :label="item.categoryName"
                :value="item.demandDetailId"
              >
                <div class="option_" @click="deviceSelect(item)">{{ item.categoryName }}</div>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="设备编码:">
            <el-input v-model="form.categoryCode" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="回收时间:">
            <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="12">
          <el-form-item label="原因">
            <el-input v-model="form.reason" type="textarea" :rows="2" :disabled="type == 'view'" />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- <headerTitle title="配件申请清单" style="margin-top: 15px"></headerTitle> -->
      <!-- <spareParts
        ref="spareCycleRef"
        :type="type"
        :source="type =='add' ? '配件回收':''"
        :state="type=='add'?'可操作':''"
        v-if="editRepairNotesDialog"
        :detailList="detailList"
      ></spareParts>-->
      <spareInfo
        ref="spareCycleRef"
        :types="type"
        title="配件回收清单"
        :detailList="detailList"
        v-if="editRepairNotesDialog"
      />
    </el-form>
    <template v-slot:footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" v-if="type == 'add'" @click="save" :loading="loading">确认</el-button>
    </template>
    <workOrderList ref="workOrderListRef" @changeSelect="changeSelect" />
  </ele-modal>
</template>
    
<script>
import spareInfo from '@/views/salesServiceManagement/accessory/components/spareInfo.vue';
import workOrderList from '@/views/salesServiceManagement/accessory/components/workOrderList.vue';
import { getCurrentUser } from '@/utils/token-util';

import {
  recycleSave,
  getSalesWorkOrderById,
  recycleDetails
} from '@/api/salesServiceManagement/index';
export default {
  props: {},
  components: { workOrderList, spareInfo },
  computed: {
    // 部门下拉
    loginChangeGroupVOList() {
      return this.$store.state.user?.info?.loginChangeGroupVOList;
    }
  },
  data() {
    return {
      loading: false,
      title: '新增',
      editRepairNotesDialog: false,
      type: 'add',
      form: {
        recycleName:'',
      },
      loginChangeRoleVOList: [],
      deviceList: [],
      detailList: []
    };
  },
  watch: {},
  methods: {
    init(row, type) {
      this.editRepairNotesDialog = true;
      this.type = type;
      this.title = type == 'add' ? '新增' : '详情';
      let currentUser = getCurrentUser()
      this.form.recycleDeptId = currentUser.currentGroupId; // 部门id
      this.roleVOListData();
      if (row?.id) {
        this.getDetail(row);
      } else {
        this.form.recycleId = currentUser.currentRoleId; // 回收人Id
        // 下拉数据 name 赋值
        this.echoData();
      }
    },
    async getDetail(row) {
      const res = await recycleDetails(row.id);
      this.detailList = res.detailList;
      this.form.code = res.code;
      this.$set(this.form, 'code', res.code);
      this.$set(this.form, 'demandDetailId', res.demandDetailId);
      this.$set(this.form, 'categoryCode', res.categoryCode);
      this.$set(this.form, 'usageTime', res.usageTime);
      this.$set(this.form, 'reason', res.reason);
      this.$set(this.form, 'contactName', res.contactName);
      this.$set(this.form, 'contactCode', res.contactCode);
      this.changeSelect(
        {
          id: res.repairId,
          name: res.orderWorkName,
          code: res.orderWorkCode
        },
        1
      );
      //    this.form.recycleId = currentUser.currentRoleId; // 回收人Id
      //    this.echoData();
      this.$set(this.form, 'recycleId', res.recycleId);
      this.$set(this.form, 'recycleName', res.recycleName);
      console.log(res, 'res 55');
      console.log(this.loginChangeRoleVOList, 'loginChangeRoleVOList --');
    },
    handleClose() {
      this.editRepairNotesDialog = false;
      this.form = {
        recycleName:''
      };
      this.$refs.recyleFormRef.resetFields();
      this.deviceList = [];
      this.detailList = [];
    },
    async save() {
      //   let validCycle = await this.$refs.spareCycleRef.getValidate();
      let list = this.$refs.spareCycleRef.getSpareData() || [];
      if (list.length == 0) {
        this.$message.warning('请至少添加一条配件申请清单');
        return;
      }
      this.$refs.recyleFormRef.validate(async (valid) => {
        if (valid) {
          let detailList = this.listData(list);
          let data = {
            ...this.form,
            detailList
          };
          const res = await recycleSave(data);
          if (res) {
            this.$message.success('操作成功');
            this.handleClose();
            this.$emit('refresh');
          }
        }
      });
    },
    listData(list) {
      let arr = [];
      if (list.length == 0) return list;
      list.map((item) => {
        this.addData(item, arr);
      });
      return arr;
    },
    addData(item, arr) {
      let totalCount = item.totalCount ? item.totalCount - 0 : '';
      if (!totalCount) {
        arr.push(item);
        return;
      }
      for (let i = 0; i < totalCount; i++) {
        item.totalCount = 1;
        arr.push(item);
      }
    },
    // 选择工单
    handHead() {
      if (this.type != 'view') {
        this.$refs.workOrderListRef.open();
      }
    },
    // 确认选择工单
    async changeSelect(row, type) {
      console.log(row, 'row ==========');
      this.$set(this.form, 'orderWorkName', row.name);
      this.$set(this.form, 'orderWorkCode', row.code);
      this.form.repairId = row.id; // 工单id
      const res = await getSalesWorkOrderById(row.id);
      this.$set(this.form, 'contactName', res.afterSalesDemandVO.contactName);
      this.$set(this.form, 'contactCode', res.afterSalesDemandVO.contactCode);
      let list = res.afterSalesDemandVO.productDetail.map((el) => {
        return {
          categoryName: el.categoryName,
          categoryCode: el.categoryCode,
          demandDetailId: el.id
        };
      });
      this.deviceList = list;
      //  type 判断是不是修改/详情进来 是的话不需要初始赋值
      if (!type) {
        this.$set(this.form, 'categoryName', list[0].categoryName);
        this.$set(this.form, 'categoryCode', list[0].categoryCode);
        this.$set(this.form, 'demandDetailId', list[0].demandDetailId);
      }
    },
    // 设备名称选择
    deviceSelect(item) {
      this.form.categoryName = item.categoryName;
      this.form.categoryCode = item.categoryCode;
      this.form.demandDetailId = item.demandDetailId;
    },
    // 领用部门/领用人 name 赋值
    echoData() {
      const depObj = this.loginChangeGroupVOList.find(
        (item) => item.groupId === this.form.recycleDeptId
      );
      const roleObj = this.loginChangeRoleVOList.find(
        (item) => item.roleId === this.form.recycleId
      );
      this.form.recycleDeptName = depObj.groupName; // 回收部门名称
      this.form.recycleName = roleObj.roleName; // 回收人名称
    },
    // 角色下拉
    roleVOListData() {
      let arr = this.loginChangeGroupVOList.find((item) => {
        return item.groupId == this.form.recycleDeptId;
      })?.loginChangeRoleVOList;
      this.loginChangeRoleVOList = arr;
    }
  }
};
</script>
    
<style lang="scss" scoped>
.device_name {
  .el-select-dropdown__wrap {
    .el-select-dropdown__item {
      padding: 0 !important;
    }
  }

  .option_ {
    width: 100%;
    padding: 0 20px;
  }
}
</style>