<template>
  <div class="app-container">
    <div class="header">
      <el-button icon="el-icon-d-arrow-left" plain type="primary" class="back" @click="goBack">返回</el-button>
      <h1>{{ '【' + carInfo.licensePlate + '】' }}车辆明细</h1>
    </div>
    <el-divider></el-divider>
    <el-descriptions class="descriptions" :column="column" border style="text-align: center;">
      <el-descriptions-item>
        <template slot="label">
          <svg-icon slot="prefix" icon-class="car" class="el-input__icon input-icon" />
          车牌号
        </template>
        {{ carInfo.licensePlate }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          <svg-icon slot="prefix" icon-class="Branding" class="el-input__icon input-icon" />
          品牌
        </template>
        {{ carInfo.brand }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          <svg-icon slot="prefix" icon-class="PhAppStoreLogoFill" class="el-input__icon input-icon" />
          车型
        </template>
        {{ carInfo.series }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          <svg-icon slot="prefix" icon-class="cost" class="el-input__icon input-icon" />
          总价（元）
        </template>
        {{ carInfo.cost }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          <svg-icon slot="prefix" icon-class="date" class="el-input__icon input-icon" />
          上牌时间
        </template>
        {{ parseTime(carInfo.acquisitionTime, '{y}-{m}-{d}') }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          <i class="el-icon-user-solid"></i>
          驾驶员
        </template>
        {{ carInfo.driverUser ? carInfo.driverUser.nickName : '' }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          <svg-icon slot="prefix" icon-class="date" class="el-input__icon input-icon" />
          预计使用年限（年）
        </template>
        {{ carInfo.expectLife }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          <svg-icon slot="prefix" icon-class="car" class="el-input__icon input-icon" />
          预计行驶里程（万千米）
        </template>
        {{ carInfo.expectKm }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          <svg-icon slot="prefix" icon-class="cost" class="el-input__icon input-icon" />
          油耗（元/km）
        </template>
        {{ carInfo.fuel }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          <svg-icon slot="prefix" icon-class="cost" class="el-input__icon input-icon" />
          保险（元/天）
        </template>
        {{ carInfo.insurance }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          <svg-icon slot="prefix" icon-class="cost" class="el-input__icon input-icon" />
          维修（元/天）
        </template>
        {{ carInfo.maintenance }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          <svg-icon slot="prefix" icon-class="JamYelpSquare" class="el-input__icon input-icon" />
          是否为租车
        </template>
        {{ carInfo.isRent == '0' ? '否' : '是' }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          <svg-icon slot="prefix" icon-class="TeenyiconsYenSolid" class="el-input__icon input-icon" />
          单日成本（元）
        </template>
        {{ carInfo.dayCost }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          <svg-icon slot="prefix" icon-class="dept" class="el-input__icon input-icon" />
          状态
        </template>
        {{ statusTypeText(carInfo.status) }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          <svg-icon slot="prefix" icon-class="remark" class="el-input__icon input-icon" />
          备注
        </template>
        {{ carInfo.remark }}
      </el-descriptions-item>
    </el-descriptions>
    <el-divider></el-divider>
    <el-row :gutter="20">
      <!-- 费用明细 -->
      <el-col :span="12" :xs="24">
        <el-card>
          <div slot="header" class="clearfix">
            <h3>维保记录</h3>
          </div>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                v-hasPermi="['car:record:add']">新增</el-button>
            </el-col>
            <!-- <el-col :span="1.5">
              <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                v-hasPermi="['car:record:edit']">修改</el-button>
            </el-col> -->
            <el-col :span="1.5">
              <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
                @click="handleDelete" v-hasPermi="['car:record:remove']">删除</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['car:record:export']">导出</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="info" plain icon="el-icon-s-release" size="mini" @click="handleScrap" v-hasPermi="['car:record:add']">{{ scrapButtonName
                }}</el-button>
            </el-col>
          </el-row>
          <el-table v-loading="loading" :data="expenseList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column type="index" width="55" align="center" label="序号" />
            <el-table-column label="负责人" align="center" prop="userId">
              <template slot-scope="scope">
                {{ scope.row.user ? scope.row.user.nickName : '' }}
              </template>
            </el-table-column>
            <el-table-column label="费用类型" align="center" prop="expenseType">
              <template slot-scope="scope">
                <el-tag :type="typeStyle(scope.row.expenseType)">{{ expenseTypeText(scope.row.expenseType) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="费用金额" align="center" prop="expense">
              <template slot-scope="scope">
                {{ scope.row.expense + '元' }}
              </template>
            </el-table-column>
            <el-table-column label="发生日期" align="center" prop="occurDate">
              <template slot-scope="scope">
                {{ scope.row.occurDate }}
              </template>
            </el-table-column>
            <el-table-column width="55" align="center" label="备注" prop="remark" />
            <el-table-column label="附件" align="center" prop="document" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                  v-hasPermi="['car:record:edit']">修改</el-button>
                <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                  v-hasPermi="['car:record:remove']">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-show="expenseTotal > 0" :total="expenseTotal" :autoScroll="false" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />
        </el-card>
      </el-col>
      <el-col :span="12" :xs="24">
        <el-card>
          <div slot="header" class="clearfix">
            <h3>派出任务</h3>
          </div>
          <el-table v-loading="loading" :data="approvalList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column type="index" width="55" align="center" label="序号" />
            <el-table-column label="申请人" align="center" prop="user.nickName">
              <template slot-scope="scope">
                {{ scope.row.applierUser ? scope.row.applierUser.nickName : '' }}
              </template>
            </el-table-column>
            <el-table-column label="使用部门" align="center" prop="dept.deptName">
              <template slot-scope="scope">
                {{ scope.row.dept ? scope.row.dept.deptName : '' }}
              </template>
            </el-table-column>
            <el-table-column label="项目编号" align="center" prop="project.projectNumber">
              <template slot-scope="scope">
                {{ scope.row.project ? scope.row.project.projectNumber : '' }}
              </template>
            </el-table-column>
            <el-table-column label="项目名称" align="center" prop="project.projectName">
              <template slot-scope="scope">
                {{ scope.row.project ? scope.row.project.projectName : '' }}
              </template>
            </el-table-column>
            <el-table-column label="开始时间" align="center" prop="beginDate">
              <template slot-scope="scope">
                {{ scope.row.beginDate }}
              </template>
            </el-table-column>
            <el-table-column label="结束时间" align="center" prop="endDate">
              <template slot-scope="scope">
                {{ scope.row.endDate }}
              </template>
            </el-table-column>
          </el-table>
          <pagination v-show="approvalTotal > 0" :total="approvalTotal" :autoScroll="false" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />
        </el-card>
      </el-col>
    </el-row>
    <!-- 添加明细 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="expenseForm" :model="expenseForm" :rules="rules" label-width="100px">
        <el-form-item label="负责人" prop="userId">
          <el-select v-model="expenseForm.userId" filterable clearable style="width:220px">
            <el-option v-for="item in userList" :key="item.userId" :label="item.nickName" :value="item.userId"
              v-if="item.nickName != 'admin'">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="费用类型" prop="expenseType">
          <el-select v-model="expenseForm.expenseType" placeholder="请选择" clearable @change="expenseTypePath">
            <el-option label="保险费" value="0"></el-option>
            <el-option label="维修/保养费" value="1"></el-option>
            <el-option label="轮胎费" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="费用金额" prop="expense">
          <el-input v-model="expenseForm.expense" placeholder="请输入费用金额" style="width:150px" /> <el-tag>元</el-tag>
        </el-form-item>
        <el-form-item label="发生日期" prop="occurDate">
          <el-date-picker clearable v-model="expenseForm.occurDate" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择发生日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注说明" prop="remark">
          <el-input type="textarea" v-model="expenseForm.remark" placeholder="请输入备注说明" style="width:220px" />
        </el-form-item>
        <el-form-item label="附件" prop="document">
          <FileUpload :limit="1" :filePathName="expenseName" :fileType="['doc', 'docx', 'xls', 'xlsx', 'pdf', 'rar', 'zip']"
            @input="getExpensePath"></FileUpload>
          <div v-if="modifyOpen">
            <transition-group class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear"
              tag="ul">
              <li key="li01" class="el-upload-list__item ele-upload-list__item-content">
                <el-link :href="`${baseUrl}${'/profile/upload' + expenseForm.document}`" :underline="false" target="_blank">
                  <span class="el-icon-document" style="color:#0011ff;text-decoration: underline;">
                    {{ getFileName(expenseForm.document) }}
                  </span>
                </el-link>
              </li>
            </transition-group>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改cmc设备报废对话框 -->
    <el-dialog :title="title" :visible.sync="scrapOpen" width="500px" append-to-body>
      <el-form ref="scrapForm" :model="scrapForm" :rules="rules" label-width="80px">
        <el-form-item label="原价值" prop="cost">
          <el-input v-model="scrapForm.cost" placeholder="请输入原价值" />
        </el-form-item>
        <el-form-item label="报废日期" prop="scrapDate">
          <el-date-picker clearable v-model="scrapForm.scrapDate" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择报废日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="报废原因" prop="reason">
          <el-input v-model="scrapForm.reason" placeholder="请输入报废原因" />
        </el-form-item>
        <el-form-item label="处理结果" prop="deal">
          <el-input v-model="scrapForm.deal" placeholder="请输入处理结果" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="scrapForm.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="附件" prop="document">
          <FileUpload :limit="1" :filePathName="'车辆/报废'" :fileType="['doc', 'docx', 'xls', 'xlsx', 'pdf', 'rar', 'zip']"
            @input="getScrapPath"></FileUpload>
          <div v-if="scrapModifyOpen">
            <transition-group class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear"
              tag="ul">
              <li key="li01" class="el-upload-list__item ele-upload-list__item-content">
                <el-link :href="`${baseUrl}${'/profile/upload' + scrapForm.document}`" :underline="false"
                  target="_blank">
                  <span class="el-icon-document" style="color:#0011ff;text-decoration: underline;">
                    {{ getFileName(scrapForm.document) }}
                  </span>
                </el-link>
              </li>
            </transition-group>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitScrapForm">确 定</el-button>
        <el-button @click="scrapCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getCar } from '@/api/oa/car/car.js'
import { listDeviceExpense, getDeviceExpense, delDeviceExpense, addDeviceExpense, updateDeviceExpense } from "@/api/oa/device/deviceExpense";
import { listDeviceScrap, getDeviceScrap, delDeviceScrap, addDeviceScrap, updateDeviceScrap } from "@/api/oa/device/deviceScrap";
import { listCarApproval } from "@/api/oa/car/carApproval";
import { listUser } from '@/api/system/user';
export default {
  data() {
    let validateExpense = (rule, value, callback) => {
      setTimeout(() => {
        if (!value) {
          return callback(new Error('请输入金额'));
        }
        if (!this.isNumber(Number(value))) {
          callback(new Error('请输入数字值'));
        } else {
          callback();
        }
      }, 100)
    }
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      column: 4,
      carInfo: {},
      expenseList: [],
      approvalList: [],
      userList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      expenseTotal: 0,
      approvalTotal: 0,
      multiple: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      title: '',
      open: false,
      modifyOpen: false,
      scrapOpen: false,
      scrapModifyOpen: false,
      expenseForm: {
        userId: 17,
      },
      scrapForm: {},
      scrapButtonName: '',
      expenseName: '',
      rules: {
        expenseType: [
          { required: true, message: '请选择费用类型', trigger: 'change' }
        ],
        expense: [
          { validator: validateExpense, required: true, trigger: 'blur' },
        ],
        occurDate: [
          { required: true, message: '请选择发生日期', trigger: 'change' },
        ],
      },
      loading: false
    }
  },
  created() {
    if (this.$route.query) {
      getCar(this.$route.query.carId).then(res => {
        this.carInfo = res.data;
      })
      this.getList();
      this.getUserList();
      this.getScrapStatus();
    }
    if (this.$store.state.app.device == 'desktop') {

    } else {
      this.column = 1
    }
  },
  methods: {
    getList() {
      this.queryParams.carId = this.$route.query.carId;
      listDeviceExpense(this.queryParams).then(res => {
        this.expenseList = res.rows;
        this.expenseTotal = res.total;
      });
      this.queryParams.cars = this.$route.query.carId;
      listCarApproval(this.queryParams).then(res => {
        this.approvalList = res.rows;
        this.approvalTotal = res.total;
      })
    },
    getUserList() {
      listUser({ pageSize: 9999, pageNum: 1 }).then(res => {
        this.userList = res.rows
      })
    },
    goBack() {
      let obj = { path: "/car/detail" }
      this.$tab.closeOpenPage(obj);
      this.$router.push({ path: '/oa/car/index' });
    },
    getScrapStatus() {
      this.queryParams.carId = this.$route.query.carId
      listDeviceScrap(this.queryParams).then(res => {
        if (res.total > 0)
          this.scrapButtonName = '查看报废信息';
        else
          this.scrapButtonName = '前往报废';
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.deviceExpenseId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加车辆明细";
    },
    handleUpdate(row) {
      this.reset();
      const deviceExpenseId = row.deviceExpenseId || this.ids
      getDeviceExpense(deviceExpenseId).then(response => {
        this.expenseForm = response.data;
        this.modifyOpen = true;
        this.open = true;
        this.title = "修改车辆明细";
      });
    },
    handleDelete(row) {
      const deviceExpenseIds = row.deviceExpenseId || this.ids;
      this.$modal.confirm('是否确认删除车辆费用编号为"' + deviceExpenseIds + '"的数据项？').then(function () {
        return delDeviceExpense(deviceExpenseIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    handleExport() {
      this.download('oa/deviceExpense/export', {
        ...this.queryParams
      }, `deviceExpense_${new Date().getTime()}.xlsx`)
    },
    // 表单重置
    reset() {
      this.expenseForm = {
        deviceExpenseId: null,
        carId: null,
        expenseType: null,
        expense: null,
        occurDate: null,
        remark: null,
      };
      this.resetForm("expenseForm");
    },
    submitForm() {
      this.$refs["expenseForm"].validate(valid => {
        if (valid) {
          this.expenseForm.carId = this.$route.query.carId
          if (this.expenseForm.deviceExpenseId != null) {
            updateDeviceExpense(this.expenseForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.modifyOpen = false;
              this.getList();
            });
          } else {
            addDeviceExpense(this.expenseForm).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    cancel() {
      this.open = false;
      this.modifyOpen = false;
      this.reset();
    },
    //费用附件路径
    getExpensePath(val) {
      let arr = val.split('/upload')
      this.expenseForm.document = arr[1]
      if (val == "") {
        this.expenseForm.document = ""
      }
    },
    //报废附件路径
    getScrapPath(val) {
      let arr = val.split('/upload')
      this.scrapForm.document = arr[1]
      if (val == "") {
        this.scrapForm.document = ""
      }
    },
    getFileName(name) {
      if (name) {
        let arr = name.split('/')
        return arr[arr.length - 1];
      }
    },
    /* 报废记录 */
    handleScrap() {
      if (this.scrapButtonName == '查看报废信息')
        this.handleUpdateScrap();
      else
        this.handleAddScrap();
    },
    handleAddScrap() {
      this.resetScrap();
      this.scrapOpen = true;
      this.title = "添加设备报废信息";
    },
    handleUpdateScrap() {
      this.resetScrap();
      this.scrapForm.carId = this.$route.query.carId
      listDeviceScrap(this.scrapForm).then(response => {
        this.scrapForm = response.rows[0];
        this.scrapOpen = true;
        this.scrapModifyOpen = true;
        this.title = "修改设备报废信息";
      });
    },
    // 表单重置
    resetScrap() {
      this.scrapForm = {
        deviceScrapId: null,
      };
      this.resetForm("scrapForm");
    },
    submitScrapForm() {
      this.$refs["scrapForm"].validate(valid => {
        if (valid) {
          this.scrapForm.carId = this.$route.query.carId
          if (this.scrapForm.deviceScrapId != null) {
            updateDeviceScrap(this.scrapForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.scrapOpen = false;
              this.scrapModifyOpen = false;
              getCar(this.$route.query.carId).then(res => {
                this.carInfo = res.data;
              });
              this.getScrapStatus();
            });
          } else {
            addDeviceScrap(this.scrapForm).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.scrapOpen = false;
              getCar(this.$route.query.carId).then(res => {
                this.carInfo = res.data;
              });
              this.getScrapStatus();
            });
          }
        }
      });
    },
    scrapCancel() {
      this.scrapOpen = false;
      this.scrapModifyOpen = false;
      this.resetScrap();
    },
    isNumber(value) {
      return typeof value === 'number' && /^\d+(\.\d+)?$/.test(value);
    },
    expenseTypePath(val) {
      if (val == '0') {
        this.expenseName = '车辆/费用/保险费'
      }
      if (val == '1') {
        this.expenseName = '车辆/费用/维修保养费'
      }
      if (val == '2') {
        this.expenseName = '车辆/费用/轮胎费'
      }
    },
    statusTypeText(row) {
      if (row == '0') {
        return '已派出'
      }
      if (row == '1') {
        return '可使用'
      }
      if (row == '2') {
        return '维修中'
      }
      if (row == '3') {
        return '已还车'
      }
      if (row == '4') {
        return '已报废'
      }
    },
    expenseTypeText(row) {
      if (row == '0') {
        return '保险费'
      }
      if (row == '1') {
        return '维修/保养费'
      }
      if (row == '2') {
        return '轮胎费'
      }
    },
    typeStyle(row) {
      if (row == '0') {
        return 'primary'
      }
      if (row == '1') {
        return 'warning'
      }
      if (row == '2') {
        return 'success'
      }
    }
  },
}
</script>

<style lang="scss" scoped>
.header {
  position: relative;
  text-align: center;

  .back {
    position: absolute;
    left: 12px;
    top: -10px;
  }
}

.descriptions {
  padding: 20px 50px;
}


::v-deep .el-descriptions-item__label.is-bordered-label {
  color: #121212;
  background: rgba($color: #46a6ff, $alpha: 0.1);
  width: 200px;
}

::v-deep .el-descriptions .is-bordered .el-descriptions-item__cell {
  border: 1px solid #2d3f62;
}
</style>