<template>
  <ele-modal
    custom-class="ele-dialog-form long-dialog-form"
    :visible.sync="visibleDialog"
    :title="title"
    :close-on-click-modal="false"
    width="85%"
    append-to-body
    @close="handleClose"
    :maxable="true"
  >
    <el-form ref="form" :model="addForm" label-width="120px">
      <el-row>
        <el-col :span="8">
          <el-form-item label="工单编码">
            <el-input
              v-model="salesForm.code"
              size="small"
              placeholder="请输入"
              disabled
            ></el-input>
          </el-form-item>
        </el-col>
        <!-- 用计划名称 -->
        <el-col :span="8">
          <el-form-item label="名称">
            <el-input
              v-model="salesForm.name"
              size="small"
              placeholder="请输入"
              disabled
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="接收人">
            <el-input
              v-model="salesForm.receptionUserName"
              size="small"
              placeholder="请输入"
              disabled
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="接收时间">
            <el-input
              v-model="salesForm.receptionTime"
              size="small"
              placeholder="请输入"
              disabled
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="派单人">
            <el-input
              v-model="salesForm.dispatchUserName"
              size="small"
              placeholder="请输入"
              disabled
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="派单时间">
            <el-input
              v-model="salesForm.dispatchTime"
              size="small"
              placeholder="请输入"
              disabled
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <!-- <el-col :span="8">
          <el-form-item
            label="实际起始时间"
            prop="time"
            :rules="{
              required: true,
              message: '实际起始时间',
              trigger: 'change'
            }"
          >
            <el-date-picker
              style="width: 100%"
              v-model="addForm.time"
              type="datetimerange"
              value-format="yyyy-MM-dd HH:mm:ss"
              range-separator="至"
              start-placeholder="实际开始日期"
              end-placeholder="实际结束日期"
              :disabled="type == 'view'"
              @change="getTime"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="实际售后时长" prop="inFactDuration">
            <el-input v-model="addForm.inFactDuration" :disabled="true">
              <template slot="append">min</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="附件" prop="attachments">
            <fileMain v-model="addForm.attachments" :type="type == 'view' ? 'view' : 'add'"></fileMain>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="故障现象" prop="faultPhenomenon">
            <el-input
              type="textarea"
              placeholder="请输入内容"
              v-model="addForm.faultPhenomenon"
              :disabled="type == 'view'"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="故障原因" prop="faultReason">
            <el-input
              type="textarea"
              placeholder="请输入内容"
              v-model="addForm.faultReason"
              :disabled="type == 'view'"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="维修过程" prop="maintenanceProcess">
            <el-input
              type="textarea"
              placeholder="请输入内容"
              v-model="addForm.maintenanceProcess"
              :disabled="type == 'view'"
            ></el-input>
          </el-form-item>
        </el-col>-->
        <!-- ***改 -->
        <div class="ele-body-custom">
          <el-tabs v-model="activeName" style="width: 100%" type="border-card">
            <el-tab-pane label="需求信息" name="需求信息">
              <el-col :span="24" class="ele-body-customA">
                <info
                  ref="infoRef2"
                  v-if="infoDisabled"
                  type="view"
                  :isPurchaseNeed="false"
                ></info>
                <info
                  ref="infoRef2"
                  v-else
                  source="售后计划"
                  state="可操作"
                  type="view"
                  :isPurchaseNeed="false"
                ></info>
              </el-col>
            </el-tab-pane>
            <el-tab-pane label="计划信息" name="计划信息">
              <planDialog ref="plan"></planDialog>
            </el-tab-pane>
            <el-tab-pane label="方案" name="方案">
              <el-col :span="24">
                <spareParts
                  ref="sparePartsRef2"
                  :state="type == 'edit' ? '可操作' : ''"
                  :type="type == 'edit' ? 'edit' : 'view'"
                  obtain="仓库"
                ></spareParts>
                <!--  source="报工信息" -->
              </el-col>
            </el-tab-pane>
            <!-- v-if="type == 'report'" 标记 -->
            <el-tab-pane
              v-if="infoShow"
              label="报工信息"
              name="报工信息"
              class="job_infor"
            >
              <el-col :span="12" class="timing">
                <el-form-item
                  label="开始时间"
                  prop="startTime"
                  :rules="{
                    required: true,
                    message: '请选择开始时间',
                    trigger: 'change'
                  }"
                >
                  <el-date-picker
                    :disabled="type == 'view'"
                    v-model="addForm.startTime"
                    type="datetime"
                    placeholder="选择开始时间"
                    format="yyyy-MM-dd HH:mm:ss"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    @change="handleTimeChange"
                  ></el-date-picker>
                </el-form-item>

                <el-form-item
                  label="结束时间"
                  prop="endTime"
                  :rules="{
                    required: true,
                    message: '请选择结束时间',
                    trigger: 'change'
                  }"
                >
                  <el-date-picker
                    :disabled="type == 'view'"
                    v-model="addForm.endTime"
                    type="datetime"
                    placeholder="选择结束时间"
                    format="yyyy-MM-dd HH:mm:ss"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    @change="handleTimeChange"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="实际售后时长"
                  prop="inFactDuration"
                  class="after_sales"
                >
                  <el-input v-model="days" :disabled="true">
                    <template slot="append">天</template>
                  </el-input>
                  <el-input v-model="hours" :disabled="true">
                    <template slot="append">小时</template>
                  </el-input>
                  <el-input v-model="minutes" :disabled="true">
                    <template slot="append">分钟</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24" class="ele-body-customA">
                <info
                  ref="infoRef"
                  source="报工信息"
                  state="可操作"
                  type="view"
                  :isReportDetails="type == 'view' ? true : false"
                  :isPurchaseNeed="false"
                ></info>
              </el-col>
              <el-col :span="24">
                <headerTitle
                  title="配件申请清单"
                  style="margin-top: 10px"
                ></headerTitle>
                <spareParts
                  ref="sparePartsRef"
                  :state="type == 'edit' ? '可操作' : ''"
                  :type="type == 'edit' ? 'edit' : 'view'"
                ></spareParts>
                <!-- source="报工信息" -->
              </el-col>
              <el-col :span="24">
                <spareInfo
                  :detailList="detailList"
                  ref="spareCycleRef"
                  :types="type"
                  title="配件回收清单"
                  v-if="visibleDialog"
                />
              </el-col>
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-row>
    </el-form>

    <div slot="footer" class="footer">
      <el-button
        type="primary"
        :loading="loading"
        @click="submitAdd"
        v-if="type != 'view'"
        >{{ type == 'edit' ? '保存' : '报工' }}</el-button
      >

      <el-button
        type="primary"
        :loading="loading"
        @click="saveAdd"
        v-if="type == 'report'"
        >保存</el-button
      >
      <el-button @click="handleClose" :loading="loading">取消</el-button>
    </div>
  </ele-modal>
</template>

<script>
  import spareInfo from '@/views/salesServiceManagement/accessory/components/spareInfo.vue';
  // import fileMain from '@/components/addDoc/index.vue';
  import {
    reportWorkingSalesWorkOrder,
    updateScheme,
    getSalesWorkOrderById
  } from '@/api/salesServiceManagement/index';
  import spareParts from '@/views/salesServiceManagement/components/sparePartsList.vue';
  import info from '@/views/salesServiceManagement/components/info.vue';
  import planDialog from './planDialog.vue';
  export default {
    props: {},
    components: {
      // fileMain,
      spareParts,
      info,
      planDialog,
      spareInfo
    },
    watch: {},
    computed: {
      infoDisabled() {
        let flag = this.type == 'view' || this.type == 'report';
        return flag;
      },
      infoShow() {
        let flag =
          this.type == 'report' ||
          this.addForm.orderStatus == 3 ||
          this.addForm.orderStatus == 4 ||
          this.addForm.orderStatus == 5;
        return flag;
      }
    },
    data() {
      return {
        activeName: '需求信息',
        title: '',
        visibleDialog: false,
        addForm: {
          id: '',
          time: [],
          attachments: [],
          reason: ''
        },
        row: {},
        type: '',
        days: 0,
        hours: 0,
        minutes: 0,
        endTime: '', // 结束时间
        startTime: '', // 开始时间
        endTimePickerOptions: {
          disabledDate: (time) => {
            // 如果开始时间已选择，禁用开始时间之前的日期
            if (this.addForm.startTime) {
              return (
                time.getTime() < new Date(this.addForm.startTime).getTime()
              );
            }
            return false;
          }
        },
        salesForm: {
          code: '',
          name: '',
          receptionUserName: '',
          receptionTime: '',
          dispatchUserName: '',
          dispatchTime: ''
        },
        detailList: [],
        loading: false
      };
    },
    created() {},
    methods: {
      open(row, type) {
        this.visibleDialog = true;
        this.type = type;
        this.title = type == 'edit' ? '修改' : type == 'view' ? '详情' : '报工';
        if (type == 'report') {
          this.activeName = '报工信息';
        } else {
          this.activeName = '需求信息';
        }
        this.getDetail(row);
      },
      async getDetail(row) {
        const res = await getSalesWorkOrderById(row.id);
        this.addForm = res;
        this.salesForm = {
          code: res.code || '',
          receptionUserName: res.receptionUserName || '',
          receptionTime: res.receptionTime || '',
          dispatchUserName: res.afterSalesPlanVO.dispatchUserName || '',
          dispatchTime: res.afterSalesPlanVO.dispatchTime || '',
          name: res.afterSalesPlanVO.name || ''
        };
        // ***
        this.$nextTick(() => {
          // *** 报工信息的
          if (this.infoShow) {
            this.detailList = res.accessoryApply?.detailList;
            this.$refs.infoRef.init(res.afterSalesDemandVO);
            this.$refs.sparePartsRef.setTableValue(res?.costListVOS || []);
            this.$refs.infoRef2.init(res.afterSalesDemandVO);
            this.$refs.sparePartsRef2.setTableValue(res?.costListVOS || []);
            this.$set(this.addForm, 'startTime', this.addForm.acceptTime);
            this.$set(this.addForm, 'endTime', this.addForm.finishTime);
            this.calculateTimeConversion(res.inFactDuration);
          } else {
            this.$refs.infoRef2.init(res.afterSalesDemandVO);
            this.$refs.sparePartsRef2.setTableValue(res?.costListVOS || []);
          }
          this.$refs.plan.init(res.afterSalesPlanVO);
        });
      },

      // 时间选择
      handleTimeChange() {
        // 如果结束时间早于开始时间，清空结束时间
        if (this.addForm.startTime && this.addForm.endTime) {
          const startTime = new Date(this.addForm.startTime).getTime();
          const endTime = new Date(this.addForm.endTime).getTime();
          if (startTime > endTime) {
            this.addForm.endTime = '';
            this.$message.warning('结束时间不能小于开始时间');
            this.days = 0;
            this.hours = 0;
            this.minutes = 0;
            return;
          }
          if (this.addForm.startTime && this.addForm.endTime) {
            this.calculateTimeDifference();
          }
        }
      },
      // 时间转换 分钟
      calculateTimeConversion(minutes) {
        if (!minutes && minutes != 0) {
          this.timeAssignment(0, 0, 0);
          return;
        }
        // 确保输入是数字
        const totalMinutes = parseFloat(minutes);
        // 计算天、小时、分钟
        const days = (totalMinutes / (24 * 60)).toFixed(1);
        const hours = (totalMinutes / 60).toFixed(1);
        this.days = days;
        this.hours = hours;
        this.minutes = minutes;
      },
      // 时间赋值
      timeAssignment(days, hours, mins) {
        // 格式化结果（保留一位小数）
        let timeDifference = {
          days: days.toFixed(1),
          hours: hours.toFixed(1),
          minutes: mins.toFixed(0)
        };
        this.days = timeDifference.days;
        this.hours = timeDifference.hours;
        this.minutes = timeDifference.minutes;
      },
      // 时间转换 年月日 时分秒
      calculateTimeDifference() {
        // 计算时间差
        const startTime = new Date(this.addForm.startTime);
        const endTime = new Date(this.addForm.endTime);
        const timeDiff = endTime - startTime; // 毫秒数
        // 转换为天、小时、分钟
        const minutes = timeDiff / (1000 * 60);
        const hours = minutes / 60;
        const days = hours / 24;
        this.timeAssignment(days, hours, minutes);
      },
      // 提交
      async submitAdd() {
        // *** 更改
        let info = this.type == 'edit' ? 'infoRef2' : 'infoRef';
        let spare = this.type == 'edit' ? 'sparePartsRef2' : 'sparePartsRef';
        let validInfo = await this.$refs[info].getValidate();
        let validSpare = await this.$refs[spare].getValidate();
        let dataA = this.$refs[info].getValue();
        let obj = this.infoData(dataA);
        this.finalSubmit(spare, this.type, obj);
      },
      // *** 需求信息参数
      infoData(data) {
        let obj = JSON.parse(JSON.stringify(data));
        obj.productDetail = obj.tableList;
        delete obj.tableList;
        obj.id = this.addForm.afterSalesDemandVO.id;
        obj.productDetail.map((el) => delete el.produceTime);
        return obj;
      },
      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 || totalCount == 1) {
          arr.push(item);
          return;
        }
        for (let i = 0; i < totalCount; i++) {
          item.totalPrice = item.singlePrice || 0;
          item.totalCount = 1;
          arr.push(item);
        }
      },
      // 最后提交 spare:具体的方案组件 obj:需求信息参数
      finalSubmit(spare, type, obj) {
        this.$refs.form.validate(async (valid) => {
          if (valid) {
            let data = {
              acceptTime: this.addForm.startTime,
              finishTime: this.addForm.endTime,
              attachments: this.addForm.attachments,
              maintenanceProcess: this.addForm.maintenanceProcess,
              faultPhenomenon: this.addForm.faultPhenomenon,
              faultReason: this.addForm.faultReason,
              inFactDuration: this.minutes,
              id: this.addForm.id,
              costListVOS: this.$refs[spare].getTableValue(),
              salesDemandUpdatePO: obj
            };
            // 报工 逻辑处理 配件申请清单数据
            if (type == 'report') {
              let list = this.$refs.spareCycleRef.getSpareData() || [];
              let detailList = this.listData(list);
              // 判断清单数据是否存在
              if (detailList.length > 0) {
                // 指定绑定第一条设备信息
                let item = data.salesDemandUpdatePO.productDetail[0];
                let accessoryApply = {
                  demandDetailId: item.id,
                  categoryCode: item.categoryCode,
                  categoryName: item.categoryName,
                  contactName: obj.contractInfo.name,
                  contactCode: obj.contractInfo.code,
                  detailList
                };
                data.accessoryApply = accessoryApply;
              }
            }
            // let api = this.type == 'edit' ? updateScheme : reportWorkingSalesWorkOrder;
            let api =
              type == 'edit' ? updateScheme : reportWorkingSalesWorkOrder;
            this.loading = true;
            await api(data)
              .then((res) => {
                this.loading = false;
                if (!res) return;
                this.$message.success('操作成功');
                this.visibleDialog = false;
                this.$emit('reload');
              })
              .catch((err) => {
                this.loading = false;
              });
          } else {
            return false;
          }
        });
      },

      // 保存
      saveAdd() {
        this.$refs.form.validate(async (valid) => {
          if (valid) {
            let dataA = this.$refs.infoRef2.getValue();
            let obj = this.infoData(dataA);
            let data = {
              acceptTime: this.addForm.startTime,
              finishTime: this.addForm.endTime,
              attachments: this.addForm.attachments,
              maintenanceProcess: this.addForm.maintenanceProcess,
              faultPhenomenon: this.addForm.faultPhenomenon,
              faultReason: this.addForm.faultReason,
              inFactDuration: this.minutes,
              id: this.addForm.id,
              costListVOS: this.$refs.sparePartsRef2.getTableValue(),
              salesDemandUpdatePO: obj
            };
            if (!data.acceptTime || !data.finishTime) {
              data.acceptTime = '';
              data.finishTime = '';
              data.inFactDuration = 0;
            }
            // 报工 逻辑处理 配件申请清单数据
            let list = this.$refs.spareCycleRef.getSpareData() || [];
            if (list.length > 0) {
              let detailList = this.listData(list);
              // 指定绑定第一条设备信息
              let item = data.salesDemandUpdatePO.productDetail[0];
              let accessoryApply = {
                demandDetailId: item.id,
                categoryCode: item.categoryCode,
                categoryName: item.categoryName,
                contactName: obj.contractInfo.name,
                contactCode: obj.contractInfo.code,
                detailList
              };
              data.accessoryApply = accessoryApply;
            }
            this.loading = true;
            await updateScheme(data)
              .then((res) => {
                this.loading = false;
                if (!res) return;
                this.$message.success('操作成功');
                this.visibleDialog = false;
                this.$emit('reload');
              })
              .catch((err) => {
                this.loading = false;
              });
          }
        });
      },
      handleClose() {
        this.visibleDialog = false;
      }
    }
  };
</script>

<style lang="scss" scoped>
  .dialog_top {
    margin-bottom: 10px;
    display: flex;
    align-items: center;

    span {
      margin-left: 50px;
    }

    .name {
      font-weight: 800;
      color: #40a9ff;
    }
  }

  ::v-deep .el-row {
    display: flex;
    flex-wrap: wrap;
  }

  .btns {
    text-align: right;
    // margin: 10px 0;
  }

  .main_container {
    width: 100%;
    display: flex;
    justify-content: space-between;
  }

  .ele-body-custom {
    width: 100%;
    margin-bottom: 24px;
  }

  .ele-body-customA {
    :deep(.divider) {
      display: none;
    }
  }

  .after_sales {
    :deep(.el-input--medium) {
      width: 30%;
    }
    :deep(.el-input--medium:nth-child(1)) {
      margin-right: 5%;
    }
    :deep(.el-input--medium:nth-child(2)) {
      margin-right: 5%;
    }
  }

  .job_infor {
    :deep(.ele-body) {
      padding: 15px 0;
    }
  }

  .timing {
    display: flex;
    :deep(.el-form-item) {
      width: 50%;

      .el-date-editor {
        width: 100%;
      }
    }
  }
</style>
