<template>
  <div v-loading="loading || detailLoading">
    <div class="drawer-head">
      <div class="cell-title">
        <div>
          <p class="title">申请使用</p>
        </div>
      </div>
      <div class="cell-btn">
        <el-button type="primary" v-if="pListData&&pListData.procInstId" @click="handleMonitor" icon="el-icon-data-line">流程监控</el-button>
        <el-button v-if="editStatus&&pListData.procInstId" type="danger" @click="deleteForm" icon="el-icon-close">撤销</el-button>
        <el-button v-if="(editStatus||workflowStatus)" type="primary" @click="submitForm" icon="el-icon-finished">提交</el-button>
        <el-button @click="close" icon="el-icon-close">关闭</el-button>
      </div>
    </div>
    <template v-if="attributeModelBool('approve') && workflowStatus">
      <div class="tboper">
        <div class="tit"> {{submitLabel}}</div>
      </div><!--tboper 标题与操作按钮-->
      <div class="el-form-border">
        <el-form>
          <el-row>
            <el-col :span="24">
              <el-form-item :label="submitLabel+'结论:'" prop="pass">
                <el-radio-group v-model.trim="formSubmit.pass">
                  <el-radio
                    v-for="dict in passoptions"
                    :key="dict.value"
                    :label="dict.value"
                  >{{ dict.label }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row >
            <el-col :span="24">
              <el-form-item :label="submitLabel+'意见:'">
                <el-input
                  v-model="formSubmit.summary"
                  type="textarea"
                  :placeholder="'请输入'+submitLabel+'意见'"
                  maxlength="200"
                  :autosize="{ minRows: 4, maxRows: 4 }"
                  :style="{ width: '100%' }"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </template>
    <div class="divide double"></div><!--divide 分隔-->
    <div class="tboper">
      <div class="tit">申请信息</div>
    </div>
    <div class="el-form-border">
      <el-form ref="eForm" :model="form" :rules="rules" label-width="150px">
        <div>
          <el-row>
            <el-col :span="24">
              <el-form-item label="申请人">
                <span>{{form.nickName}}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="申请部门" prop="deptId">
                <span>{{form.deptName}}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="申请理由" prop="reason">
                <el-input :readonly="!editStatus" v-model="form.reason" type="textarea" :rows="3" maxlength="1000" show-word-limit></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
    </div><!--el-form-border 表单-->
    <div class="divide double"></div><!--divide 分隔-->
    <div class="tboper">
      <div class="tit">申请工具</div>
    </div><!--tboper 标题与操作按钮-->
    <div class="el-form-border">
      <el-form ref="form" label-width="150px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="编号">{{applyToolDetail ? applyToolDetail.toolCode:''}}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="中文别名">{{applyToolDetail ? applyToolDetail.toolName:''}}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人">{{applyToolDetail ? applyToolDetail.toolPrincipalsName:''}}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="归属单位">{{applyToolDetail ? applyToolDetail.toolRespDeptName:''}}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="来源">
              <dict-tag :options="dict.type.tool_source" :value="applyToolDetail.toolSource"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用途">{{applyToolDetail ? applyToolDetail.toolUse:''}}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类别">
              <dict-tag :options="dict.type.tool_type" :value="applyToolDetail.toolType"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="形态">
              <dict-tag :options="dict.type.tool_status" :value="applyToolDetail.status"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="加密方式">{{applyToolDetail ? applyToolDetail.encryptionMode:''}}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="服务时间">{{applyToolDetail ? applyToolDetail.serviceTime:''}}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人">{{applyToolDetail ? applyToolDetail.contactPerson:''}}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式">{{applyToolDetail ? applyToolDetail.contactPhone:''}}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="测评机构">{{applyToolDetail ? applyToolDetail.testSituation:''}}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="功能简介">{{applyToolDetail ? applyToolDetail.functionDesc:''}}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="适用条件">{{applyToolDetail ? applyToolDetail.applyCondition:''}}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="操作说明">{{applyToolDetail ? applyToolDetail.operateExplain:''}}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注">{{applyToolDetail ? applyToolDetail.remark:''}}</el-form-item>
          </el-col>
        </el-row>
      </el-form><!--el-form-->
    </div>

    <!-- 流程选择下一环节及人员  开始 -->
    <el-dialog
      title="选择下一环节及人员"
      v-if="dialogVisible" :visible.sync="dialogVisible"
      width="60%"
      append-to-body
      v-loading = flowStepLoading
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <processcode
        ref="prochild"
        :searchQuery="searchQuery"
        :pListData="pListData"
        :isSummary="isSummary"
      ></processcode>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleWorkflowSubmit"
        >提 交</el-button
        >
      </span>
    </el-dialog>
    <!-- 流程选择下一环节及人员  结束 -->
    <monitor-drawer
      v-if="monitorDrawerVisible"
      ref="monitorDrawer"
    ></monitor-drawer>
    <bl-user-selector  ref="peopleSelect" :type="'single'" :isCheck="true" :open="toolPrincipalsChoose" @cancel="toolPrincipalsChoose=false"   @submit="submitPeople"></bl-user-selector>
  </div>
</template>
<script>
import { listDocument } from "@/api/document/document";
import processcode from "@/views/workflowList/processcode/index.vue";
import {
  workflowprocesskey,
  getStartActdef,
  getExtAttributeModel,
  procInstInfoAndStatus,
} from '@/api/my_business/workflow'
import WorkflowLogs from '@/views/workflowList/workflowLogs/index.vue'
import AddDoc from '@/views/tool/AddDoc.vue'
import Treeselect from '@riophae/vue-treeselect'
import { deptTreeSelect } from "@/api/system/user";
import { addApply, getInfoByBpmcId, updateApply } from '@/api/tool/toolApply'
import { listItem } from '@/api/tool/userApplyItem'
import blUserSelector from '@/components/user-selector/src/user-selector.vue'
import { getTool } from "@/api/tool/tool";
import store from "@/store";

// PDF本地文件预览
export default {
  dicts: ['sys_normal_disable','tool_type', 'tool_source', 'tool_status'],
  components: {
    blUserSelector,
    Treeselect, AddDoc,
    WorkflowLogs,
    processcode,
  },
  name: "Borrow_doc",
  props: ['data'],
  data() {
    return {
      toolPrincipalsChoose: false,
      // 新增时的关联附件
      dataList: [],
      applyToolDetail: {},
      addDocShow: false,
      defaultStaff: [],
      yes: 'Y',
      searchQuery: {},
      deptList: [],
      companyList: [],
      deptOptions: [],
      docClassList: [],
      submitLabel:undefined,
      passoptions: [
        { value: true, label: "通过" },
        { value: false, label: "不通过" },
      ],
      formSubmit: { summary: "", actionType: "", pass: true },
      isSummary: false,
      activeName: "info",
      nodeDetail: [],
      procDefKey: undefined,
      viewId: "",
      userInfo: this.$store.getters.userInfo,
      viewShow: false,
      monitorDrawerVisible:false,
      form: {},
      rules: {
        userId: [
          { required: true, message: "申请人不能为空", trigger: "blur" }
        ],
        reason: [
          { required: true, message: '申请理由不能为空', trigger: 'blur' }
        ]
      },
      kuozhanshuju: {},
      kuozhanshujuBool: {},
      kuozhanshujuLabel: {},
      pListData: {},
      editStatus:false,
      workflowStatus: false,
      dialogVisible: false,
      loading: false,
      detailLoading: false,
      flowStepLoading : false,
      // 默认密码
      initPassword: undefined,
    };
  },
  computed: {},
  watch: {
    data (val) {
      if (val) {
        this.init(val)
      }
    },
  },
  mounted() {
    if (this.data) {
      this.init(this.data)
    }
    this.getConfigKey("sys.user.initPassword").then(response => {
      this.initPassword = response.msg;
    });
    this.getDeptTree()
  },
  methods: {
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    async init(row) {
      let _this = this
      _this.rest(row)
      _this.loading = true
      _this.procDefKey = 'Process_DCMGS6M9'
      _this.form.type = row.type
      //是否编辑模式
      _this.$nextTick(() => {
        if (row && row.procInstId) {
          let procInstId = row.procInstId
          _this.workflowStatus = row.status == '1'
          _this.procInstInfoAndStatus(procInstId)
          _this.getDetail(procInstId)
        } else {
          _this.workflowStatus = true
          _this.loading = false
          _this.editStatus = true
          _this.getWorkflowprocesskey();
        }
      });
    },
    getDetail(procInstId) {
      let _this = this
      _this.detailLoading = true
      getInfoByBpmcId(procInstId).then(async (res) => {
        let formData = res.data;
        formData.type = _this.form.type
        _this.form = formData
        this.getItemList(res.data.id);
      }).finally(()=>{
        _this.detailLoading = false
      });
    },
    getItemList(id){
      let _this = this
      listItem({applyId:id}).then(res=>{
        _this.dataList = res.data
      })
      getTool(_this.form.toolId).then((response) => {
        _this.applyToolDetail = response.data;
      });
    },
    rest(data){
      let _this = this
      _this.activeName = "info"
      _this.dataList = [{...data}]
      _this.applyToolDetail = {...data}
      _this.form={
        userId:_this.userInfo.userId,
        nickName:_this.userInfo.nickName,
        deptId:_this.userInfo.deptId,
        deptName:_this.userInfo.dept.deptName,
        reason: ""
      }
    },
    procInstInfoAndStatus(procInstId){
      let _this = this
      procInstInfoAndStatus(procInstId).then((res) => {
        if (res) {
          _this.pListData = res
        }else {
          _this.pListData = {procInstId:procInstId}
        }
        _this.getExtAttributeModel()
      });
    },
    getWorkflowprocesskey() {
      let _this = this
      _this.loading = true
      _this.pListData = {}
      if (_this.procDefKey) {
        workflowprocesskey(_this.procDefKey).then((data) => {
          getStartActdef(data.data.procDefId).then((res) => {
            _this.pListData = res.data;
            this.getExtAttributeModel()
          });
        });
      }else {
        _this.$message.warning("该文件类型尚未进行流程设置，将无法发起流程！");
      }
    },
    getExtAttributeModel(){
      let _this = this
      let procDefId = _this.pListData.procDefId
      let curActDefId = _this.pListData.curActDefId || _this.pListData.actDefId
      if (procDefId&&curActDefId) {
        getExtAttributeModel(
          procDefId,
          curActDefId
        ).then((res) => {
          let kuozhanshujuBool = {}
          let kuozhanshuju = {}
          let kuozhanshujuLabel = {}
          res.data.forEach(item=>{
            kuozhanshujuLabel[item.objKey] = item.objName
            if (item.objType==='Boolean') {
              kuozhanshujuBool[item.objKey] = item.objValue
            } else {
              kuozhanshuju[item.objKey] = item.objValue
            }
          })
          _this.kuozhanshujuBool = kuozhanshujuBool;
          _this.kuozhanshuju = kuozhanshuju;
          _this.kuozhanshujuLabel = kuozhanshujuLabel;
          _this.editStatus =_this.attributeModelBool('edit')&&_this.workflowStatus
          _this.submitLabel = _this.attributeModelLabel('approve')
        }).finally(()=>{
          _this.loading = false
        });
      }else {
        _this.kuozhanshujuBool = {}
        _this.kuozhanshuju = {}
        _this.loading = false
      }
    },
    attributeModelBool(val){
      if (this.kuozhanshujuBool&&this.kuozhanshujuBool!=={}) {
        let obj = this.kuozhanshujuBool[val]
        return obj?obj==='true':false
      }else {
        return false
      }
    },
    attributeModel(val){
      return this.kuozhanshuju[val]
    },
    attributeModelLabel(val){
      return this.kuozhanshujuLabel[val]
    },
    close() {
      this.viewShow = false;
      this.$emit("close")
    },
    // 提交
    async saveForm() {
      let _this = this
      // 首先页签调整为 信息内容
      _this.activeName = 'info'
      if (!_this.procDefKey) {
        _this.$message.warning("尚未进行流程设置，将无法发起流程！");
        return;
      }
      let dialogVisible = true
      if (!!_this.$refs["eForm"]) {
        let valid = await _this.$refs["eForm"].validate()
        if (!valid) {
          dialogVisible = false
        }
      }
      _this.tempForm()
    },
    //不需要验证必填的保存
    tempForm() {
      let _this = this
      if (!_this.procDefKey) {
        _this.$message.warning("尚未进行流程设置，将无法发起流程！");
        return;
      }
      _this.loading = true
      let formData = JSON.parse(JSON.stringify(_this.form))
      formData.itemList = _this.dataList
      formData.recordStatus = "draft";
      formData.editStatus = _this.editStatus
      if (formData.id) {
        updateApply(formData).then((res) => {
          if (res.code===200) {
            _this.$message({
              message: '保存成功',//提示的信息
              type:'success',　　//类型是成功
              duration:1200,　　//显示时间, 毫秒。设为 0 则不会自动关闭，建议1200
            });
          }
        }).finally(()=>{
          _this.loading = false
        });
      } else {
        let wf_receivers = [];
        wf_receivers.push({
          receiveUserId: _this.userInfo.userName,
          receiveUserOrgId: _this.userInfo.deptId
        });
        let wf_procTitle = "【使用申请】"+_this.dataList[0].toolName
        formData.bpmClientInputModel = {
          model: {
            wf_procDefId: _this.pListData.procDefId,
            wf_procDefKey: _this.procDefKey,
            wf_procTitle: wf_procTitle,
            wf_sendUserId: _this.userInfo.userName,
            wf_sendUserOrgId: _this.userInfo.deptId,
            wf_receivers: wf_receivers,
            wf_curActDefName: _this.pListData.actDefName,
            wf_curActDefId: _this.pListData.actDefId,
            wf_nextActDefName: _this.pListData.actDefName,
            wf_nextActDefId: _this.pListData.actDefId,
          },
          type: formData.type,
          review: _this.attributeModelBool('approve'),
        };
        formData.editStatus = _this.editStatus
        addApply(formData).then((res) => {
          if (res.code===200) {
            _this.form.id = res.data.businessKey;
            _this.procInstInfoAndStatus(res.data.procInstId)
            _this.$message({
              message: '保存成功',//提示的信息
              type:'success',　　//类型是成功
              duration:1200,　　//显示时间, 毫秒。设为 0 则不会自动关闭，建议1200
            });
          }
        }).finally(()=>{
          _this.loading = false
        });
      }
    },
    deleteForm(){
      let _this = this
      _this.$modal.confirm('撤销后，该流程待办任务将会被删除，请谨慎操作。是否确认执行？')
        .then(()=> {
          _this.loading = true
          let formData = {
            id: _this.form.id,
            bpmClientInputModel: {
              model: {
                wf_procDefKey: _this.procDefKey,
                wf_procDefId: _this.pListData.procDefId,
                wf_procInstId: _this.pListData.procInstId,
                wf_sendUserId: _this.userInfo.userName,
                wf_sendUserOrgId: _this.userInfo.deptId,
                wf_curActDefName: _this.pListData.curActDefName,
                wf_curActDefId: _this.pListData.curActDefId,
              },
            },
            review: false,
            recordStatus: 'cancel',
            editStatus: false
          }
          addApply(formData).then((res) => {
            if (res.code === 200) {
              this.$modal.msgSuccess("撤销成功");
              this.close(true);
            }
          });
        })
    },
    // 提交
    async submitForm() {
      let _this = this
      // 首先页签调整为 信息内容
      _this.activeName = 'info'
      if (!_this.procDefKey) {
        _this.$message.warning("尚未进行流程设置，将无法发起流程！");
        return;
      }
      let dialogVisible = true
      //审核
      if (_this.attributeModelBool('approve')) {
        if (_this.formSubmit.pass==='') {
          _this.$modal.msgError(_this.submitLabel+"结论不能为空！");
          return true;
        } else if (!_this.formSubmit.pass&&!_this.formSubmit.summary) {
          _this.$modal.msgError("请填写"+_this.submitLabel+"意见");
          return true;
        }
      }
      if (!!_this.$refs["eForm"]) {
        let valid = await _this.$refs["eForm"].validate()
        if (!valid) {
          dialogVisible = false
        }
      }
      _this.searchQuery.pass = _this.formSubmit.pass
      let defaultStaff = []
      this.defaultStaff=defaultStaff
      this.dialogVisible = true;
    },

    //提交表单和流程数据
    handleWorkflowSubmit() {
      let _this = this
      let formData = JSON.parse(JSON.stringify(_this.form))
      formData.itemList = _this.dataList
      let wf_receivers = [];
      if (_this.$refs.prochild.receiveUserList.length < 1 &&_this.$refs.prochild.nextData.actDefType!=='endEvent') {
        _this.$message.warning("请选择人员！");
        return;
      }
      _this.$refs.prochild.receiveUserList.forEach((element) => {
        wf_receivers.push({
          receiveUserId: element.id,
          receiveUserOrgId: element.parentId,
        });
      });
      let wf_nextActDefId = _this.$refs.prochild.nextData.actDefId;
      let wf_nextActDefName = _this.$refs.prochild.nextData.actDefName;
        // 显示加载中
        _this.flowStepLoading = true
        _this.detailLoading = true
      let wf_procTitle = "【使用申请】"+_this.dataList[0].toolName
        if (_this.pListData && _this.pListData.procInstId) {
          //流程执行参数
          formData.bpmClientInputModel = {
            model: {
              wf_procDefKey: _this.procDefKey,
              wf_procDefId: _this.pListData.procDefId,
              wf_procTitle: wf_procTitle,
              wf_curActInstId: _this.pListData.curActInstId,
              wf_sendUserId: _this.userInfo.userName,
              wf_sendUserOrgId: _this.userInfo.deptId,
              wf_receivers: wf_receivers,
              wf_nextActDefId: wf_nextActDefId,
              wf_curComment: _this.formSubmit.summary,
              wf_curActDefId: _this.pListData.curActDefId,
              wf_curActDefName: _this.pListData.curActDefName,
              wf_nextActDefName: wf_nextActDefName,
            },
            applyStatus: _this.formSubmit.pass,
            review: _this.attributeModelBool('approve'),
            type: formData.type
          };
        }else{
          //创建流程参数
          formData.bpmClientInputModel = {
            model: {
              wf_procTitle:  wf_procTitle,
              wf_nextActDefId: wf_nextActDefId,
              wf_procDefId: _this.pListData.procDefId,
              wf_procDefKey: _this.procDefKey,
              wf_sendUserId: _this.userInfo.userName,
              wf_sendUserOrgId: _this.userInfo.deptId,
              wf_receivers: wf_receivers,
              wf_curActDefName: _this.pListData.actDefName,
              wf_curActDefId: _this.pListData.actDefId,
              wf_nextActDefName: wf_nextActDefName,
            },
            review: _this.attributeModelBool('approve'),
            type: formData.type,
          };
        }
        if (_this.$refs.prochild.nextData.actDefType==='endEvent') {
          //办结
          formData.recordStatus = 'done'
        } else {
          //进行中
          formData.recordStatus = 'doing'
        }
        formData.editStatus = _this.editStatus
        addApply(formData).then((res) => {
          if (res.code===200) {
            _this.$message({
              message: '流程提交成功',//提示的信息
              type:'success',　　//类型是成功
              duration:1200,　　//显示时间, 毫秒。设为 0 则不会自动关闭，建议1200
              onClose:()=>{
                _this.flowStepLoading = false
                _this.detailLoading = false
                _this.dialogVisible = false;
                _this.close();
              }
            });

            store.dispatch('GetUserMsgCount').then(() => { })
          }
        });
    },
    handleMonitor() {
      this.monitorDrawerVisible = true;
      this.$nextTick(() => {
        this.$refs.monitorDrawer.init(this.pListData.procInstId);
      });
    },
    handleDelete(dataList,index){
      dataList.splice(index,1)
    },
    /**
     * 新增上传附件
     */
    handleDocAdd() {
      this.addDocShow = true
    },
    submitPeople(peopleList){
      this.$set(this.form,'userId',peopleList[0]['userId'])
      this.$set(this.form,'nickName',peopleList[0]['nickName'])
      this.$set(this.form,'deptId',peopleList[0]['deptId'])
      this.$set(this.form,'deptName',peopleList[0].dept.deptName)
      this.toolPrincipalsChoose = false;
      this.$refs['eForm'].validateField("userId");
    },
  },
};
</script>
