<template>
  <div class="app-container">
    <el-drawer
      v-if="onOpen"
      :visible.sync="onOpen"
      ref="drawer"
      direction="rtl"
      size="50%"
      @close="closeCallBack"
    >
      <template slot="title">
        <div>临时工程申请 【{{ title }}】</div>
      </template>
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        v-loading="loading"
        label-width="100px"
        style="padding-left: 25px; padding-right: 25px"
      >
        <div class="mycanvas">
          <div class="canvas" ref="flowCanvas"></div>
          <div class="maskLayer" />
        </div>
        <el-form-item label="项目单位">
          {{ form.parProjName }}
        </el-form-item>
        <el-form-item label="项目名称" prop="projId">
          <el-select
            v-model="form.projId"
            placeholder="请选择项目名称"
            style="width: 100%"
            filterable
            @change="projectChage"
          >
            <el-option
              v-for="(item, index) in projectOptions"
              :key="index"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="申请类型">
          {{ title }}
        </el-form-item>
        <el-form-item label="申请人">
          <label
            >{{ nickName }} <el-tag type="info" size="mini">{{ deptName }}</el-tag></label
          >
        </el-form-item>
        <el-form-item label="申请原因" prop="applyReason">
          <el-input
            type="textarea"
            v-model="form.applyReason"
            placeholder="请输入申请原因"
            rows="3"
          />
        </el-form-item>
        <el-form-item label="附件说明" prop="applyFiles">
          <FileUpload
            :limit="9"
            v-model="form.applyFiles"
            :fileType="['pdf', 'png', 'jpg', 'jpeg', 'doc', 'docx', 'xls', 'xlsx']"
          />
        </el-form-item>
        <el-divider content-position="left" style="margin-left">申请明细信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="handleAddProProjectApplyDetail"
              >添加</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="handleDeleteProProjectApplyDetail"
              >删除</el-button
            >
          </el-col>
        </el-row>
        <el-table
          :data="proProjectApplyDetailList"
          :row-class-name="rowProProjectApplyDetailIndex"
          @selection-change="handleProProjectApplyDetailSelectionChange"
          ref="proProjectApplyDetail"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50" />
          <el-table-column align="center" prop="assetsId">
            <template slot="header" slot-scope="scope">
              <span class="required">申请明细</span>
            </template>
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.assetsId"
                placeholder="请选择申请明细"
                filterable
                style="width: 100%"
                @change="selectAssetsId"
              >
                <el-option-group
                  v-for="group in AssetsTypeOptions"
                  :key="group.id"
                  :label="group.name"
                >
                  <el-option
                    v-for="item in group.childrenAssetsTypeList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-option-group>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="number" align="center" width="180">
            <template slot="header" slot-scope="scope">
              <span class="required">申请数量</span>
            </template>
            <template slot-scope="scope">
              <el-row>
                <el-col :span="12"
                  ><el-input v-model="scope.row.number" placeholder="数量"
                /></el-col>
                <el-col :span="12"
                  ><el-select
                    v-model="scope.row.assetsUnit"
                    placeholder="单位"
                    filterable
                  >
                    <el-option
                      v-for="(item, index) in getUnitOptions(scope.row.assetsId)"
                      :key="index"
                      :label="item"
                      :value="item"
                    >
                    </el-option> </el-select
                ></el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column
            v-if="showAssetsVersion"
            label="申请规格"
            align="center"
            prop="assetsVersion"
            width="180"
          >
            <template slot-scope="scope">
              <el-input
                type="textarea"
                v-model="scope.row.assetsVersion"
                placeholder="请输入申请规格"
                rows="2"
                maxlength="200"
              />
            </template>
          </el-table-column>
          <el-table-column prop="useReason" align="center">
            <template slot="header" slot-scope="scope">
              <span class="required">使用说明</span>
            </template>
            <template slot-scope="scope">
              <el-input
                type="textarea"
                v-model="scope.row.useReason"
                placeholder="请输入申请规格"
                rows="2"
                maxlength="500"
              />
            </template>
          </el-table-column>
        </el-table>
        <div style="text-align: center; margin: 20px 0px">
          <el-button type="primary" @click="submitForm">提交申请</el-button>
          <el-button @click="doCanel">取 消</el-button>
        </div>
      </el-form>
    </el-drawer>
  </div>
</template>

<script>
import store from "@/store";
import { definitionStart, flowXmlAndNode } from "@/api/flowable/definition";
import { CustomViewer as BpmnViewer } from "@/components/customBpmn";
import { getNextFlowNodeByStart } from "@/api/flowable/todo";
import { findMyDeptProject } from "@/api/project/projectInfo";
import { findAllByCategory } from "@/api/base/assetsType";

export default {
  components: {},
  props: {
    closeCallBack: {
      type: Function,
    },
  },
  data() {
    return {
      // 抽屉层
      onOpen: false,
      // 遮罩层
      loading: false,
      // 标题
      title: "",
      // 表单参数
      form: {
        id: null,
        deptId: null,
        projId: 0,
        projName: null,
        parProjName: null,
        applyType: null,
        applyStatus: null,
        applyReason: null,
        applyFiles: null,
        applyUser: null,
        useTime: null,
        isDel: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
      },
      // 表单校验
      rules: {
        projId: [{ required: true, message: "请选择项目名称", trigger: "blur" }],
        applyReason: [{ required: true, message: "请输入申请原因", trigger: "blur" }],
      },
      projectOptions: [],
      deptName: null,
      nickName: null,
      bpmnViewer: null,
      options: {},
      taskTitle: null,
      taskOpen: false,
      proProjectApplyDetailList: [],
      // 子表选中数据
      checkedProProjectApplyDetail: [],
      showAssetsVersion: false,
      AssetsTypeOptions: [],
      unitOptions: [],
    };
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  beforeDestroy() {},
  methods: {
    // 查询和我相关的项目信息
    initMyProject() {
      // 获取项目列表的接口
      findMyDeptProject().then((response) => {
        if (response.code == 200) {
          this.projectOptions = response.data;
          if (response.data.length > 0) {
            this.form.projId = response.data[0].id;
            this.form.projName = response.data[0].name;
          }
        }
      });
    },
    initCategoryAssetsType(val) {
      // 获取项目列表的接口
      findAllByCategory(val).then((response) => {
        if (response.code == 200 && response.data) {
          this.AssetsTypeOptions = response.data;
        }
      });
    },
    // 项目选择
    projectChage(val) {
      this.$forceUpdate();
      for (let i = 0; i < this.projectOptions.length; i++) {
        if (this.projectOptions[i].id == val) {
          this.form.projName = this.projectOptions[i].name;
          return false;
        }
      }
    },
    doCanel() {
      this.onOpen = false;
    },
    reset() {
      this.checkedProProjectApplyDetail = [];
      this.proProjectApplyDetailList = [];
      this.form = {};
    },
    show(options) {
      this.reset();
      this.options = options;
      this.initMyProject();
      //物资设备类需要输入规格
      if (options.category == 1) {
        this.showAssetsVersion = true;
      } else {
        this.showAssetsVersion = false;
      }
      this.initCategoryAssetsType(options.category);
      this.title = options.name;
      this.form.applyType = options.category;
      this.form.parProjName = store.getters.parDeptName;
      this.nickName = store.getters.name;
      this.deptName = store.getters.dept.deptName;
      const self = this;
      this.onOpen = true;
      flowXmlAndNode({ deployId: options.deploymentId }).then((res) => {
        this.initFlowImage(res.data.xmlData);
      });
    },
    async initFlowImage(data) {
      try {
        self.bpmnViewer = new BpmnViewer({
          container: this.$refs.flowCanvas,
          height: "100px",
        });
        await self.bpmnViewer.importXML(data);
        // 自适应
        self.bpmnViewer.get("canvas").zoom("fit-viewport", "auto");
      } catch (err) {
        console.error(err.message, err.warnings);
      }
    },
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.proProjectApplyDetailList.length == 0) {
            this.$modal.msgWarning("请添加申请明细信息...");
            return false;
          }
          for (let i = 0; i < this.proProjectApplyDetailList.length; i++) {
            if (!this.proProjectApplyDetailList[i].assetsId) {
              this.$modal.msgWarning("申请明细第 ”" + (i + 1) + "“行未选择...");
              return false;
            }
            if (!this.proProjectApplyDetailList[i].number) {
              this.$modal.msgWarning("申请明细第 ”" + (i + 1) + "“行数量未输入...");
              return false;
            }
            if (!this.proProjectApplyDetailList[i].assetsUnit) {
              this.$modal.msgWarning("申请明细第 ”" + (i + 1) + "“行单位未选择...");
              return false;
            }
            if (!this.proProjectApplyDetailList[i].useReason) {
              this.$modal.msgWarning("申请明细第 ”" + (i + 1) + "“行申请说明未输入...");
              return false;
            }
          }
          this.form.proProjectApplyDetailList = this.proProjectApplyDetailList;
          this.loading = true;
          definitionStart(this.options.id, this.form).then((res) => {
            this.$modal.msgSuccess(res.msg);
            this.loading = false;
            //关闭并刷新列表
            this.$refs.drawer.closeDrawer();
          });
        }
      });
    },
    /** 项目申请明细序号 */
    rowProProjectApplyDetailIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 项目申请明细添加按钮操作 */
    handleAddProProjectApplyDetail() {
      let obj = {};
      obj.superTypeId = "";
      obj.superTypeName = "";
      obj.typeId = "";
      obj.typeName = "";
      obj.assetsId = "";
      obj.assetsName = "";
      obj.assetsUnit = "";
      obj.number = "";
      obj.useTime = "";
      obj.useReason = "";
      obj.price = "";
      obj.totalPrice = "";
      obj.isDel = "";
      obj.remark = "";
      this.proProjectApplyDetailList.push(obj);
    },
    /** 项目申请明细删除按钮操作 */
    handleDeleteProProjectApplyDetail() {
      if (this.checkedProProjectApplyDetail.length == 0) {
        this.$modal.msgError("请先选择要删除的项目申请明细数据");
      } else {
        const proProjectApplyDetailList = this.proProjectApplyDetailList;
        const checkedProProjectApplyDetail = this.checkedProProjectApplyDetail;
        this.proProjectApplyDetailList = proProjectApplyDetailList.filter(function (
          item
        ) {
          return checkedProProjectApplyDetail.indexOf(item.index) == -1;
        });
      }
    },
    /** 复选框选中数据 */
    handleProProjectApplyDetailSelectionChange(selection) {
      this.checkedProProjectApplyDetail = selection.map((item) => item.index);
    },
    selectAssetsId(val) {
      for (let i = 0; i < this.AssetsTypeOptions.length; i++) {
        for (
          let x = 0;
          x < this.AssetsTypeOptions[i].childrenAssetsTypeList.length;
          x++
        ) {
          if (this.AssetsTypeOptions[i].childrenAssetsTypeList[x].id == val) {
            if (this.getUnitOptions(val) == null) {
              this.unitOptions.push({
                id: val,
                data: this.AssetsTypeOptions[i].childrenAssetsTypeList[x].unit.split(","),
              });
            }
          }
        }
      }
    },
    getUnitOptions(val) {
      for (let i = 0; i < this.unitOptions.length; i++) {
        if (this.unitOptions[i].id == val) {
          return this.unitOptions[i].data;
        }
      }
      return null;
    },
  },
};
</script>
<style>
.bjs-powered-by {
  display: none !important;
}
.maskLayer {
  width: 100%;
  height: 100px;
  position: absolute;
  z-index: 9999;
  top: 66px;
}
.required:before {
  content: "*";
  color: #ff4949;
  margin-right: 4px;
}
</style>
