<template>
  <div class="app-container">
    <div v-if="isLoadingStatus" />
    <div v-else>
      <el-card class="box-card">
        <div class="text item">
          <el-steps v-if="currentNode.clazz !== undefined && currentNode.clazz !== null && currentNode.clazz !== ''" :active="activeIndex" finish-status="success">
            <template v-for="(item, index) in nodeStepList">
              <el-step
                v-if="item.isHideNode === false ||
                  item.isHideNode === undefined ||
                  item.isHideNode == null ||
                  item.id === processStructureValue.workOrder.current_state"
                :key="index"
                :title="item.label"
              />
            </template>
          </el-steps>
          <div v-else>
            <el-alert
              show-icon
              title="未找到当前工单流程信息，请确认当前工单绑定的流程是否存在。"
              type="warning"
            />
          </div>
        </div>
      </el-card>

      <el-alert
        v-if="activeIndex !== nodeStepList.length && processStructureValue.workOrder.is_end===1"
        style="margin-top: 15px"
        :title="alertMessage"
        type="error"
        :closable="false"
      />

      <el-card class="box-card" style="margin-top: 15px">
        <div slot="header" class="clearfix">
          <span>公共信息</span>
        </div>
        <div class="text item">
          <el-form label-width="100px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="标题:" style="margin-bottom: 5px">
                  <span>{{ processStructureValue.workOrder.title }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="优先级:" style="margin-bottom: 0">
                  <span v-if="processStructureValue.workOrder.priority===2">
                    <el-tag type="warning">紧急</el-tag>
                  </span>
                  <span v-else-if="processStructureValue.workOrder.priority===3">
                    <el-tag type="danger">非常紧急</el-tag>
                  </span>
                  <span v-else>
                    <el-tag type="success">一般</el-tag>
                  </span>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-card>

      <el-card class="box-card" style="margin-top: 15px;">
        <div slot="header" class="clearfix">
          <span>表单信息</span>
          <!-- {{ (currentNode.hideTpls!==undefined &&
                currentNode.hideTpls!==null &&
                currentNode.hideTpls.indexOf(tplItem.form_structure.id)!==-1) ||
                (currentNode.writeTpls===undefined ||
                currentNode.writeTpls===null ||
                currentNode.writeTpls.indexOf(tplItem.form_structure.id)===-1)||
                (isActiveProcessing && currentNode.activeOrder)? true: false}} -->
        </div>
        <div class="text item">
          <template v-for="(tplItem, tplIndex) in processStructureValue.tpls">
            <fm-generate-form
              v-show="currentNode.hideTpls===undefined ||
                currentNode.hideTpls===null ||
                currentNode.hideTpls.indexOf(tplItem.form_structure.id)===-1"
              :key="tplIndex"
              :ref="'generateForm-'+tplItem.id"
              :preview="true"
              :remote="remoteFunc"
              :value="tplItem.form_data"
              :data="tplItem.form_structure"
              :organ-list="organList"
            />
          </template>
        </div>
        <div v-if="processStructureValue.userAuthority && is_end == 0">
          <hr style="background-color: #d9d9d9; border:0; height:1px; margin-bottom: 15px">
          <el-form ref="dataFrom" label-position="left" :model="dataList" label-width="150">
            <el-form-item label="备注信息" prop="remarks" :rules="[{ required: true, message: '请输入备注信息', trigger: 'blur' }]">
              <el-input
                v-model="dataList.remarks"
                type="textarea"
                placeholder="请输入备注信息"
                maxlength="200"
                :autosize="{ minRows: 3, maxRows: 99}"
                show-word-limit
              />
            </el-form-item>
          <div class="text item" style="text-align: center;margin-top:18px">
            <el-button
              v-for="(item, index) in btn_group"
              :key="index"
              :type="item.className"
              @click="submitAction(item)" >{{ item.labelShow }}</el-button>

            <!-- 拒绝按钮内置 -->
            <el-button
              v-if="endNodeDetail.id"
              type="danger"
              @click="submitAction(endNodeDetail)" >{{ endNodeDetail.label }}</el-button>
            <!-- <div
              v-if="isActiveProcessing && currentNode.activeOrder"
            >
              <el-button
                v-permisaction="['process:list:handle:active']"
                type="primary"
                @click="activeOrderActive"
              >
                主动接单
              </el-button>
            </div>
            <div v-else> -->
              <!-- <template v-for="(item, index) in processStructureValue.edges">
                <el-button
                  v-if="processStructureValue.workOrder.is_end===0 && item.source===currentNode.id"
                  :key="index"
                  type="primary"
                  @click="submitAction(item)"
                >
                  {{ item.label }}
                </el-button>
              </template> -->
            <!-- </div> -->
          </div>
          </el-form>
        </div>
      </el-card>

      <el-card class="box-card" style="margin-top: 15px">
        <div slot="header" class="clearfix">
          <span>工单流转历史</span>
        </div>
        <div class="text item">
          <el-table
            :data="circulationHistoryList"
            border
            style="width: 100%"
          >
            <el-table-column
              prop="state"
              label="节点"
            />
            <el-table-column
              prop="circulation"
              label="流转"
            />
            <el-table-column
              prop="processor"
              label="处理人"
            />
            <el-table-column
              prop="create_time"
              label="处理时间"
            />
            <el-table-column
              prop="remarks"
              label="备注"
            />
          </el-table>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import {
  GenerateForm
} from '@/components/VueFormMaking'
import 'form-making/dist/FormMaking.css'
Vue.component(GenerateForm.name, GenerateForm)

import {
  processStructure,
  handleWorkOrder,
  activeOrder,
  asyncPlayLog,
  queryUserInfo,
  queryAllOrgan
} from '@/api/process/work-order'
import store from '@/store'
import { getInfo } from '@/api/user'

import { listUser } from '@/api/system/sysuser'

import { mapGetters } from 'vuex'
export default {
  data() {
    return {
      isLoadingStatus: true,
      currentNode: {
        hideTpls: null,
        writeTpls: null
      },
      isActiveProcessing: false,
      tpls: [],
      organList: [],
      dataList: {
        remarks: '', // 备注信息
      },
      alertMessage: '',
      nodeStepList: [],
      circulationHistoryList: [],
      activeIndex: 0,
      processStructureValue: {
        workOrder: { title: '' }
      },
      endNodeDetail: {}, // 结束结节信息
      ruleForm: {
        title: '',
        process: '',
        classify: '',
        state_id: '',
        state: '',
        source_state: '',
        processor: '',
        process_method: '',
        tpls: [],
        tasks: []
      },
      userIds: null,
      tenantId: 1,
      btn_group: [],
      is_end: 0, // 是否结束
      ownerApply: false, // 是否是自己提交的申请
      remoteFunc: {
        // 获取用户列表
        userList(resolve) {
          listUser({
            pageSize: 999999
          }).then(response => {
            const options = response.data.list
            resolve(options)
          })
        }
      }
    }
  },
  computed: {
    ...mapGetters([
      'userId'
    ])
  },
  async created() {
    await this.getUserInfo()
    await this.getAllOrgan()
    await this.getProcessNodeList()
    // 获取用户信息
    try {
        let user = await getInfo()
        this.userInfo = user.data
        console.log(this.processStructureValue.workOrder.creator, user.data.userId)
        this.ownerApply = this.processStructureValue.workOrder.creator == user.data.userId ? true : false
    } catch {
        //
    }
  },
  methods: {
    async getUserInfo() {
      await queryUserInfo().then(res => {
        console.log(res)
        if(res.code == 200) {
          this.userIds = res.data.id
          this.tenantId = res.data.tenantId
        } else {
          this.$message.error(res.data)
        }
      })
    },
    async getProcessNodeList() {
      await processStructure({
        processId: this.$route.query.processId,
        workOrderId: this.$route.query.workOrderId,
        userId: this.userIds
      }).then(response => {
        let tempData = response.data.tpls;
        console.log(response);
        // 获取对应模板中，下拉框的key, value
        let selectList = this.getSelectValueObject(tempData);
        console.log(selectList);

        // 获取对应模板中，需要隐藏的字段
        let hiddenFormList = this.getSelectValueObject(
          tempData,
          "hiddenForm",
          selectList
        );

        tempData.forEach((temp, index) => {
          let tempList = temp.form_structure.list || [];
          tempList.forEach(item => {
            if (hiddenFormList[index].length > 0) {
              if (item.type != "text" && !item.options.relationStatus) {
                item.hidden = true;
              } else {
                item.hidden = false;
              }
              // item.hidden = false
              if (hiddenFormList[index].includes(item.model)) {
                item.hidden = false;
              }
            } else {
              item.hidden = false;
            }
            // 子表单
            if (item.type == "subform") {
              let childList = item.columns || [];
              let subFormStatus = true;
              childList.forEach(child => {
                let childList = child.list || [];
                childList.forEach(c => {
                  if (hiddenFormList[index].length > 0) {
                    if (c.type != "text" && !c.options.relationStatus) {
                      c.hidden = true;
                    } else {
                      c.hidden = false;
                      subFormStatus = false;
                    }
                    if (hiddenFormList[index].includes(c.model)) {
                      c.hidden = false;
                      subFormStatus = false;
                    }
                  } else {
                    c.hidden = false;
                    subFormStatus = false;
                  }
                });
              });
              item.hidden = subFormStatus;
            }
          });
        });
        this.isActiveProcessing = false
        this.processStructureValue = response.data
        this.circulationHistoryList = this.processStructureValue.circulationHistory
        // 获取当前展示节点列表
        this.nodeStepList = []
        if(this.processStructureValue.nodes) {
          for (var i = 0; i < this.processStructureValue.nodes.length; i++) {
            if (this.processStructureValue.nodes[i].id === this.processStructureValue.workOrder.current_state) {
              // 当前节点
              this.nodeStepList.push(this.processStructureValue.nodes[i])
              this.activeIndex = this.nodeStepList.length - 1
              if (i + 1 === this.processStructureValue.nodes.length) {
                this.activeIndex = this.nodeStepList.length
              }
              this.currentNode = this.processStructureValue.nodes[i]
            } else if (!this.processStructureValue.nodes[i].isHideNode) {
              // 非隐藏节点
              this.nodeStepList.push(this.processStructureValue.nodes[i])
            }
          }
        }

        // 如果回退到初始节点则可编辑。
        if (this.activeIndex === 0 && this.currentNode.clazz === 'start') {
          this.currentNode.writeTpls = []
          for (var tplTmp of this.processStructureValue.tpls) {
            this.currentNode.writeTpls.push(tplTmp.form_structure.id)
          }
        }

        // 判断是否需要主动处理
        for (var stateValue of this.processStructureValue.workOrder.state) {
          if (this.processStructureValue.workOrder.current_state === stateValue.id && stateValue.processor.length > 1) {
            this.isActiveProcessing = true
            break
          }
        }

        const nodes = this.processStructureValue.nodes
        for (var i = 0; i < nodes.length; i++) {
            // 判断节点里面是否有结束节点，而且一个流程里面只能有一个结束结点，
            if(nodes[i].clazz == 'end') {
                this.endNodeDetail = JSON.parse(JSON.stringify(nodes[i]))
                this.endNodeDetail.target = nodes[i].id
                this.endNodeDetail.flowProperties = 0 // 拒绝属性
                this.endNodeDetail.label = '拒绝'
            }
        }

        let psv = response.data.edges || []
        let btn_group = []
        psv.forEach(item => {
            // 过滤其它类型的操作
            if(this.processStructureValue.workOrder.is_end===0 && item.source===this.currentNode.id && item.flowProperties == 1) {
                if(item.flowProperties == 1) {
                    item.className = 'primary'
                    item.labelShow = '同意'
                } else if(item.flowProperties == 0) {
                    item.className = 'danger'
                } else if(item.flowProperties == 2) {
                    item.className = 'primary'
                }
                btn_group.push(item)
            } else {
                item.className = 'primary'
            }
        })
        this.btn_group = btn_group

        this.isLoadingStatus = false
        this.getAlertMessage()
      })
    },
     getSelectValueObject(tpls, type = "value", tplValues = []) {
      const tempData = tpls || [];
      let selectList = [];
      tempData.forEach((temp, index) => {
        let tempList = temp.form_structure.list || [];
        let tempSelectList = tplValues[index] || [];
        let listArray = [];
        tempList.forEach(list => {
          if (list.type == "select") {
            if (type == "value") {
              const result = this.getFormDataDetail(temp.form_data, list.model);
              if (result.status) {
                listArray.push(result);
              }
            } else {
              let selectOptions = [];
              let selectValue = [];
              tempSelectList.forEach(tsl => {
                if (tsl.model == list.model) {
                  selectOptions = list.options.options || [];
                  selectValue = tsl.value || [];
                }
              });
              selectOptions.forEach(so => {
                if (selectValue.includes(so.value)) {
                  let tempRo = so.relationOptions || [];
                  listArray.push(...tempRo);
                }
              });
            }
          }
          if (list.type == "subform") {
            let childList = list.columns || [];
            childList.forEach(child => {
              let childList = child.list || [];
              childList.forEach(c => {
                if (c.type == "select") {
                  if (type == "value") {
                    const originObj = JSON.parse(JSON.stringify(c));
                    const result = this.getFormDataDetail(
                      temp.form_data,
                      originObj.model
                    );
                    if (result.status) {
                      listArray.push(result);
                    }
                  } else {
                    let selectOptions = [];
                    let selectValue = [];
                    tempSelectList.forEach(tsl => {
                      if (tsl.model == c.model) {
                        selectOptions = c.options.options || [];
                        selectValue = tsl.value || [];
                      }
                    });
                    selectOptions.forEach(so => {
                      if (selectValue.includes(so.value)) {
                        let tempRo = so.relationOptions || [];
                        listArray.push(...tempRo);
                      }
                    });
                  }
                }
              });
            });
          }
        });
        selectList.push(listArray);
      });
      return selectList;
    },
    // 获取对应元素的值
    getFormDataDetail(formData, model) {
      let modelStatus = {
        status: false,
        value: null
      };
      for (let data in formData) {
        if (typeof formData[data] == "object") {
          // 没有子表单里面有子表单
          for (let child in formData[data]) {
            if (child == model) {
              modelStatus = {
                status: true,
                model: child,
                value: formData[data][child]
                  ? formData[data][child].split(",")
                  : []
              };
            }
          }
        } else {
          if (data == model) {
            modelStatus = {
              status: true,
              model: data,
              value: formData[data] ? formData[data].split(",") : []
            };
          }
        }
      }
      return modelStatus;
    },
    submitAction(item) {
      var promiseList = []
      this.tpls = []
      for (var tpl of this.processStructureValue.tpls) {
        this.tpls.push({
          tplDataId: tpl.id,
          tplId: tpl.form_structure.id
        })
        promiseList.push(this.$refs['generateForm-' + tpl.id][0].getData())
      }
      this.$refs['dataFrom'].validate(_ => {
        if(_) {
          Promise.all(promiseList).then(values => {
            for (var tplDataIndex in this.tpls) {
              this.tpls[tplDataIndex].tplValue = values[tplDataIndex]
            }

            let fileList = []
            this.tpls && this.tpls.forEach(tpl => {
                for(let val in tpl.tplValue) {
                    if(val.indexOf('file') != -1) {
                        const file = tpl.tplValue[val] || []
                        file.forEach(item => {
                            fileList.push(item.url)
                        })
                    }
                }
            })
            handleWorkOrder({
              tasks: this.processStructureValue.process.task,
              source_state: this.processStructureValue.workOrder.current_state,
              target_state: item.target,
              circulation: item.label,
              flow_properties: item.flowProperties === undefined ? 2 : parseInt(item.flowProperties),
              work_order_id: parseInt(this.$route.query.workOrderId),
              remarks: this.dataList.remarks,
              tpls: this.tpls
            }).then(async (response) => {
              if (response.code === 200) {
              // this.$router.push({ name: 'upcoming' })

                await asyncPlayLog({ workOrderId: parseInt(this.$route.query.workOrderId), fileUrl: fileList.join(',') })
              // window.location.reload()
                this.getProcessNodeList()

                await store.dispatch('user/getInitData')
              }
            })
          })
        }
      })
    },
    // 获取提示消息
    getAlertMessage() {
      if (this.processStructureValue.workOrder.is_end === 1) {
        this.alertMessage = '当前工单已结束。'
      }
    },
    activeOrderActive() {
      var jsonData = [{
        id: this.nodeStepList[this.activeIndex].id,
        label: this.nodeStepList[this.activeIndex].label,
        process_method: 'person',
        processor: [this.userId]
      }]
      activeOrder(jsonData, this.$route.query.workOrderId).then(() => {
        this.getProcessNodeList()
      })
    },
    async getAllOrgan() {
      await queryAllOrgan({ tenantId: this.tenantId }).then(res => {
        if (res.code == 200) {
          const result = res.data;
          const filterOrganId = [36, 39, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 52, 54, 55, 56]
          let tempOrgan = []
          // 过滤不会显示的分部
          result.forEach(item => {
            if (!filterOrganId.includes(item.id)) {
              tempOrgan.push(item)
            }
          })
          this.organList = tempOrgan
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
/deep/ .el-step__title {
  font-size: 14px;
  line-height: 1.3;
  width: 80%;
  padding-top: 10px;
}
</style>