<template>
  <div class="app-container">
    <!-- 添加或修改预约开票申请对话框 -->
    <el-dialog  :close-on-click-modal="false"  :title="$t('提交申请')" :visible.sync="visible" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item :label="$t('申请开票')">
          <el-table :data="devList" border style="width: 100%;">
            <el-table-column label="作业单位" align="center" prop="workUnit" :formatter="workUnitFormat"/>
            <el-table-column label="作业区域" align="center" prop="workArea" :formatter="workAreaFormat"/>
            <el-table-column label="单元号" align="center" prop="unitNumber" :formatter="unitNumberFormat"/>
            <el-table-column label="楼层位置" align="center" prop="floorLocation" :formatter="floorLocationFormat"/>
            <el-table-column label=" 作业开始时间" align="center" prop="workStartTime" width="100">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.workStartTime, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="作业结束时间" align="center" prop="workEndTime" width="100">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.workEndTime, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="联系人" align="center" prop="contact" :show-overflow-tooltip="true"/>
            <el-table-column label="联系方式" align="center" prop="phonenumber" :show-overflow-tooltip="true"/>
            <el-table-column label="状态" align="center" prop="status" width="100" :formatter="statusFormat"/>
          </el-table>
        </el-form-item>
        <el-form-item label="内容">
          <el-input type="textarea" :placeholder="$t('原因')+$t('空格')+$t('描述')"
                    v-model="form.content"
                    maxlength="200" show-word-limit
                    :autosize="{ minRows: 2, maxRows: 10}"></el-input>
        </el-form-item>
        <el-form-item :label="$t('附件')" prop="fileUrl">
          <el-upload
            ref="doc"
            :limit="5"
            :headers="doc.headers"
            :action="doc.url"
            :disabled="doc.isUploading"
            :on-progress="handleFileDocProgress"
            :on-success="handleFileDocSuccess"
            :on-remove="handleRemove"
            :auto-upload="true"
            :file-list="fileList"
            drag
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              {{ $t('将文件拖到此处，或') }}
              <em>{{ $t('点击上传') }}</em>
            </div>
            <div v-if="showDelay" class="el-upload__tip" slot="tip">{{ this.fileTips }}</div>
          </el-upload>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('用户主管')" prop="userSupId">
              <el-select v-model="form.userSupId" filterable :placeholder="$t('请选择') + $t('用户主管')" disabled>
                <el-option
                  v-for="dict in managerOptions"
                  :key="dict.userId"
                  :label="dict.nickName"
                  :value="dict.userId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
<!--        <el-row>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="装置主管" prop="devSupId">-->
<!--              <el-select v-model="form.devSupId" filterable :placeholder="$t('请选择') + $t('装置主管')">-->
<!--                <el-option-->
<!--                  v-for="dict in managerOptions"-->
<!--                  :key="dict.userId"-->
<!--                  :label="dict.nickName"-->
<!--                  :value="dict.userId">-->
<!--                </el-option>-->
<!--              </el-select>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--        </el-row>-->
        <el-row>
          <el-col :span="12">
            <el-form-item v-if="this.isToday" label="装置工程师" prop="devEngineerId">
              <el-select v-model="form.devEngineerId" filterable :placeholder="$t('请选择') + $t('装置工程师')">
                <el-option
                  v-for="dict in managerOptions"
                  :key="dict.userId"
                  :label="dict.nickName"
                  :value="dict.userId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item v-if="this.isSpecial" :label="$t('装置经理')" prop="managerconId">
              <el-select v-model="form.managerconId" filterable :placeholder="$t('请选择') + $t('装置经理')">
                <el-option
                  v-for="dict in managerOptions"
                  :key="dict.userId"
                  :label="dict.nickName"
                  :value="dict.userId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
<!--        <el-row>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="班长" prop="monitorId">-->
<!--              <el-select v-model="form.monitorId" filterable :placeholder="$t('请选择') + $t('班长')">-->
<!--                <el-option-->
<!--                  v-for="dict in managerOptions"-->
<!--                  :key="dict.userId"-->
<!--                  :label="dict.nickName"-->
<!--                  :value="dict.userId">-->
<!--                </el-option>-->
<!--              </el-select>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--        </el-row>-->
      </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>
  </div>
</template>

<script>
import {
  listInvoice,
  getInvoice,
  delInvoice,
  addInvoice,
  updateInvoice,
  exportInvoice,
  importTemplate
} from "@/api/invoice/invoice";
import {treeselect} from "@/api/system/dept";
import {getToken} from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import Editor from '@/components/Editor';
import {listPostUser} from "@/api/system/user";
import log from "@/views/monitor/job/log";

export default {
  name: "Invoice",
  components: {Treeselect},
  data() {
    return {
      isToday: false,
      isSpecial: false,
      doc: {
        file: "",
        // 是否显示弹出层（报告附件）
        open: false,
        // 弹出层标题（报告附件）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 报告附件上传位置编号
        ids: 0,
        showDelay: false,
        fileList: [],
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/sems/specfile/uploadFile",
        commonfileList: null,
        pType: 'traning',
        pId: null
      },
      // 遮罩层
      loading: true,
      managerOptions: [],
      devList: [],
      form: {},
      // 状态字典
      statusOptions: [],
      // 作业单位字典
      workUnitOptions: [],
      // 作业区域字典
      workAreaOptions: [],
      // 单元号字典
      unitNumberOptions: [],
      // 楼层字典
      floorLocationOptions: [],
      // 用户单位字典
      userUnitOptions: [],
      // 用户主管字典
      userMgOptions: [],
      // 作业类型字典
      workTypeOptions: [],
      // 风险等级字典
      riskLevelOptions: [],
      // 监护人单位字典
      guardianUnitOptions: [],
      visible: false,
      rules: {
        userSupId: [
          {required: true, message: this.$t('用户主管') + this.$t('不能为空'), trigger: "blur"}
        ],
        managerconId: [
          {required: true, message: this.$t('装置经理') + this.$t('不能为空'), trigger: "blur"}
        ],
        devEngineerId: [
          {required: true, message: this.$t('装置工程师') + this.$t('不能为空'), trigger: "blur"}
        ]
      }

    }
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    //设置表格高度对应屏幕高度
    this.$nextTick(() => {
      this.clientHeight = document.body.clientHeight - 250
    })
    // this.getList();
    this.getTreeselect();

  },
  methods: {
    //附件上传中处理
    handleFileDocProgress(event, file, fileList) {
    },
    handleRemove(file, fileList) {
      this.fileList = fileList
    },
    //附件上传成功处理
    handleFileDocSuccess(response, file, fileList) {
      this.fileList = fileList
      if (response.code == 200) {
        this.$alert(this.$t('导入成功'), this.$t('导入结果'), {dangerouslyUseHTMLString: true});
      } else {
        this.$alert(response.msg, this.$t('导入结果'), {dangerouslyUseHTMLString: true});
      }

    },
    init(rows) {
      this.reset();
      this.fileList = [];
      this.getDicts("booking_work_status").then(response => {
        this.statusOptions = response.data;
      });
      this.getDicts("book_work_area").then(response => {
        this.workAreaOptions = response.data;
      });
      this.getDicts("book_unit_number").then(response => {
        this.unitNumberOptions = response.data;
      });
      this.getDicts("book_floor_location").then(response => {
        this.floorLocationOptions = response.data;
      });
      this.getDicts("book_user_mg").then(response => {
        this.userMgOptions = response.data;
      });
      this.getDicts("book_user_unit").then(response => {
        this.userUnitOptions = response.data;
      });
      this.getDicts("book_work_unit").then(response => {
        this.workUnitOptions = response.data;
      });
      this.getDicts("book_work_type").then(response => {
        this.workTypeOptions = response.data;
      });
      this.getDicts("book_risk_level").then(response => {
        this.riskLevelOptions = response.data;
      });
      this.getDicts("book_guardian_unit").then(response => {
        this.guardianUnitOptions = response.data;
      });

      // this.form.devEngineerId=10082;
      // this.form.managerconId=10084;
      console.log(this.form)
      this.devList = rows;
      console.log(this.devList)
      if (rows[0].bookingworkticket.workStartTime === rows[0].createdate){
          this.isToday = true;
          this.form.isToday = 1;
      }

      if (rows[0].workType === 1 || rows[0].workType === 2 || rows[0].workType === 15) {
        this.isSpecial = true;
         this.form.isSpecial = 1;
      }
      this.form.invoiceId=rows[0].bookingticketId;
      this.form.userSupId=rows[0].bookingworkticket.userMg;
      listPostUser({
        // postCode: 'wxjl'
      }).then(response => {
        this.managerOptions = response;
    //    console.log(this.managerOptions)
      });
      this.visible = true
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.files = []
          if (this.fileList.length > 0) {
            for (let i = 0; i < this.fileList.length; i++) {
              let obj = {}
              obj.fileName = this.fileList[i].name
              obj.fileUrl = this.fileList[i].response.msg
              this.form.files.push(obj)
            }
          }

          if (this.form.workStartTime && this.form.workStartTime === this.form.createdate){
               this.form.isToday = 1;
          }

          if (this.form.workType === 1 || this.form.workType === 2 || this.form.workType === 15) {
            this.form.isSpecial = 1;
          }
          addInvoice(this.form).then(response => {
            this.msgSuccess(this.$t('新增成功'));
            this.visible = false;
             this.getList();
          })
        }
      });
    },
    // 状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 字典翻译
    workUnitFormat(row, column) {
      return this.selectDictLabel(this.workUnitOptions, row.workUnit);
    },
    // 字典翻译
    workAreaFormat(row, column) {
      return this.selectDictLabel(this.workAreaOptions, row.workArea);
    },
    // 字典翻译
    unitNumberFormat(row, column) {
      return this.selectDictLabel(this.unitNumberOptions, row.unitNumber);
    },
    // 字典翻译
    floorLocationFormat(row, column) {
      return this.selectDictLabel(this.floorLocationOptions, row.floorLocation);
    },
    // 字典翻译
    userMgFormat(row, column) {
      return this.selectDictLabel(this.userMgOptions, row.userMg);
    },
    // 字典翻译
    userUnitFormat(row, column) {
      return this.selectDictLabel(this.userUnitOptions, row.userUnit);
    },
    // 字典翻译
    workTypeFormat(row, column) {
      return this.selectDictLabel(this.workTypeOptions, row.workType);
    },
    // 字典翻译
    riskLevelFormat(row, column) {
      return this.selectDictLabel(this.riskLevelOptions, row.riskLevel);
    },
    // 字典翻译
    guardianUnitFormat(row, column) {
      return this.selectDictLabel(this.guardianUnitOptions, row.guardianUnit);
    },
    // 取消按钮
    cancel() {
      this.visible = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        managerconId: null,
        userSupId: null,
        devEngineerId: null,
        monitorId: null,
        devType: null,
        approveType: null,
        content: null,
        fileUrls: null,
        status: 0,
        creattime: null,
        enddate: null,
        processId: null,
        apNo: null,
        delFlag: null,
        deptId: null,
        devSupId: null
      };
      this.resetForm("form");
    }
  }
};
</script>
