<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="调出部门" prop="deptOutName">
        <el-input
          v-model="queryParams.deptOutName"
          placeholder="请输入调出部门"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="调出人" prop="userOutName">
        <el-input
          v-model="queryParams.userOutName"
          placeholder="请输入调出人"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="领用部门" prop="deptName">
        <el-input
          v-model="queryParams.deptName"
          placeholder="请输入领用部门"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="领用人" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入领用人"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>


      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['assets:allot:add']"
        >新增
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="success"-->
      <!--          icon="el-icon-edit"-->
      <!--          size="mini"-->
      <!--          :disabled="single"-->
      <!--          @click="handleUpdate"-->
      <!--          v-hasPermi="['assets:allot:edit']"-->
      <!--        >修改-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="danger"-->
      <!--          icon="el-icon-delete"-->
      <!--          size="mini"-->
      <!--          :disabled="multiple"-->
      <!--          @click="handleDelete"-->
      <!--          v-hasPermi="['assets:allot:remove']"-->
      <!--        >删除-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="warning"-->
      <!--          icon="el-icon-download"-->
      <!--          size="mini"-->
      <!--          @click="handleExport"-->
      <!--          v-hasPermi="['assets:allot:export']"-->
      <!--        >导出-->
      <!--        </el-button>-->
      <!--      </el-col>-->
    </el-row>

    <el-table v-loading="loading" :data="allotList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>

      <el-table-column label="调出部" align="center" prop="deptOutName"/>
      <el-table-column label="调出人" align="center" prop="userOutName"/>
      <el-table-column label="领用部门" align="center" prop="deptName"/>
      <el-table-column label="领用人" align="center" prop="userName"/>
      <el-table-column label="调拨物资" align="center" prop="allotName"/>
      <el-table-column label="状态" align="center" prop="state" :formatter="statusFormat"/>
      <el-table-column label="创建时间" align="center" prop="createTime"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="300">
        <template slot-scope="scope">
          <template v-if="scope.row.instanceId==null">
            <el-button
              type="success"
              icon="el-icon-edit"
              size="small"
              @click="commit(scope.row)"
              v-hasPermi="['assets:input:edit']"
            >提交审核
            </el-button>
            <el-button
              type="success"
              icon="el-icon-edit"
              size="small"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['assets:allot:edit']"
            >修改
            </el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="small"
              @click="handleDelete(scope.row)"
              v-hasPermi="['assets:allot:remove']"
            >删除
            </el-button>
          </template>
          <template v-if="scope.row.instanceId!=null">
            <template v-if="scope.row.taskId==undefined">
              <el-button
                size="small" type="success"
                @click="showForms(scope.$index, scope.row)">查看
              </el-button>
              <el-button
                size="small" type="warning"
                @click="showImage(scope.$index, scope.row)">进度查看
              </el-button>
            </template>
          </template>
          <template v-if="scope.row.taskId!=undefined">
            <el-button
              type="success"
              icon="el-icon-edit"
              size="small"
              @click="recommit(scope.row)"
              v-hasPermi="['assets:allot:edit']"
            >重新提交审核
            </el-button>
            <el-button
              size="small" type="success"
              @click="showForms(scope.$index, scope.row)">查看
            </el-button>
            <el-button
              size="small" type="warning"
              @click="showImage(scope.$index, scope.row)">进度查看
            </el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改资产调拨对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="调出部门" prop="depOutId">
              <treeselect v-model="form.depOutId"
                          :options="deptOptions"
                          @select="selectDepart"
                          placeholder="请选择归属部门"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="调出人">
              <el-select v-model="form.leadOutUserId" @change="changeSelect" clearable placeholder="全部">
                <el-option
                  v-for="item in userOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="物资" prop="stockValue">
          <el-select v-model="form.stockValue" multiple placeholder="请选择">
            <el-option
              v-for="item in stockOption"
              :key="item.aId"
              :label="item.aNumber+'-'+item.aName"
              :value="item.aId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="领用部门" prop="depId">
              <treeselect
                v-model="form.depId"
                :options="deptOptions"
                @select="selectAllotDepart"
                placeholder="请选择归属部门"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="领用人" prop="leadUserId">
              <el-select v-model="form.leadUserId" clearable placeholder="全部">
                <el-option
                  v-for="item in userAllotOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="form.remark" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <template v-if="form.taskId==undefined">
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </template>
        <template v-else-if="form.taskId!=undefined">
          <el-button type="primary" @click="remoiit">提交审核</el-button>
        </template>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--查看审核流程表单-->
    <el-dialog :close-on-click-modal="false" :title="hforms.title" :visible.sync="hforms.open" width="1000px">
      <!--历史表单组件-->
      <addEnterprise ref="addEnterprise"/>
    </el-dialog>

    <el-dialog :close-on-click-modal="false" :title="activitiImg.title" :visible.sync="activitiImg.open" width="1000px">
      <el-image :src="activitiImg.src"></el-image>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listAllot,
    getAllot,
    delAllot,
    addAllot,
    commit,
    recommit,
    updateAllot,
    exportAllot
  } from '@/api/assets/allot'

  import { outlistStock } from '@/api/assets/stock'

  import { selectlist } from '@/api/system/user'

  import { assetsTreeselect } from '@/api/system/dept'
  import Treeselect from '@riophae/vue-treeselect'
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'
  //历史流程表单
  import addEnterprise from '@/views/activiti/formsActiviti/index.vue'

  //流程开始
  import { getByKey } from '@/api/activiti/definition'

  export default {
    name: 'Allot',
    components: { Treeselect, addEnterprise },
    data() {
      return {
        userOptions: undefined,
        userAllotOptions: undefined,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 资产调拨表格数据
        allotList: [],
        // 弹出层标题
        title: '',
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          deptOutName: undefined,
          userOutName: undefined,
          deptName: undefined,
          userName: undefined,
          instanceId: undefined,
          state: undefined
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          depOutId: [
            { required: true, message: '调出部门id不能为空', trigger: 'blur' }
          ],
          leadOutUserId: [
            { required: true, message: '调出人id不能为空', trigger: 'blur' }
          ],
          depId: [
            { required: true, message: '领用部门id不能为空', trigger: 'blur' }
          ],
          stockValue: [
            { required: true, message: '领用物资不能为空', trigger: 'blur' }
          ],
          leadUserId: [
            { required: true, message: '领用人不能为空', trigger: 'blur' }
          ]
        },
        // 部门树选项
        deptOptions: [],
        //物资选项集合
        stockOption: [],
        stockValue: [],
        hforms: {
          title: '查看审核流程',
          open: false,
          data: []
        },
        activitiImg: {
          title: '查看审核流程图',
          open: false,
          src: ''
        },
        instanceId: ''
      }
    },
    created() {
      this.processDefinitionKey()
      this.getList()
      this.getTreeselect()
    },
    methods: {
      /** 查询部门下拉树结构 */
      getTreeselect() {
        assetsTreeselect().then(response => {
          this.deptOptions = response.data
        })
      },
      /** 查询资产调拨列表 */
      getList() {
        this.loading = true
        listAllot(this.queryParams).then(response => {
          this.allotList = response.rows
          this.total = response.total
          this.loading = false
        })
      },
      // 取消按钮
      cancel() {
        this.open = false
        this.reset()
      },
      // 表单重置
      reset() {
        this.form = {
          aId: undefined,
          depOutId: undefined,
          leadOutUserId: null,
          depId: undefined,
          leadUserId: null,
          remark: undefined,
          instanceId: undefined,
          taskId: undefined,
          state: undefined,
          createBy: undefined,
          createTime: undefined,
          updateBy: undefined,
          updateTime: undefined,
          stockValue: []
        }
        this.userOptions = []
        this.stockOption = []
        this.userAllotOptions = []
        this.resetForm('form')
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1
        this.getList()
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm('queryForm')
        this.handleQuery()
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.aId)
        this.single = selection.length != 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset()
        this.open = true
        this.title = '添加资产调拨'
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset()
        const aId = row.aId || this.ids
        getAllot(aId).then(response => {
          this.form = response.data
          let depOutId = this.form.depOutId
          selectlist(depOutId).then(response => {
            this.userOptions = response.data
            this.outlistStock(depOutId, '', 0)

          })
          let depId = this.form.depId
          selectlist(depId).then(response => {
            this.userAllotOptions = response.data
          })
          this.form.leadOutUserId = this.form.leadOutUserId + ''
          this.form.leadUserId = this.form.leadUserId + ''
          this.open = true
          this.title = '修改资产调拨'
        })
      },
      checkData(datas, values) {
        var objs = []
        for (var i = 0; i < datas.length; i++) {
          for (var j = 0; j < values.length; j++) {
            if (datas[i].aId != ('' + values[j])) {
              objs.push(j)
            }
          }
        }
        for (var i = 0; i < objs.length; i++) {
          values.baoremove(i)
        }
      },
      /** 提交按钮 */
      submitForm: function() {
        this.$refs['form'].validate(valid => {
          if (valid) {
            if (this.form.aId != undefined) {
              updateAllot(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess('修改成功')
                  this.open = false
                  this.getList()
                } else {
                  this.msgError(response.msg)
                }
              })
            } else {
              addAllot(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess('新增成功')
                  this.open = false
                  this.getList()
                } else {
                  this.msgError(response.msg)
                }
              })
            }
          }
        })
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const aIds = row.aId || this.ids
        this.$confirm('是否确认删除资产调拨编号为"' + aIds + '"的数据项?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function() {
          return delAllot(aIds)
        }).then(() => {
          this.getList()
          this.msgSuccess('删除成功')
        }).catch(function() {
        })
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams
        this.$confirm('是否确认导出所有资产调拨数据项?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function() {
          return exportAllot(queryParams)
        }).then(response => {
          this.download(response.msg)
        }).catch(function() {
        })
      },
      // 获取当前选中部门的名称
      selectDepart(val) {
        this.form.leadOutUserId = undefined
        selectlist(val.id).then(response => {
          this.userOptions = response.data
          this.outlistStock(val.id, '', 0)
        })
      },
      changeSelect(value) {
        this.outlistStock('', value, 0)
      },
      // 获取当前选中部门的名称
      selectAllotDepart(val) {
        selectlist(val.id).then(response => {
          this.userAllotOptions = response.data
        })
      },
      //获取资源数据
      outlistStock(depId, userId, status) {
        outlistStock(depId, userId, status).then(response => {
          this.stockOption = response.data
          console.log(this.stockOption)
          this.checkData(this.stockOption, this.form.stockValue)
        })
      },
      statusFormat(row, column) {
        var restatus = ''
        let obj = row.state
        switch (obj) {
          case 0:
            restatus = '审核中'
            break
          case 1:
            restatus = '不通过'
            break
          case 2:
            restatus = '通过'
            break
          default:
            restatus = '未提交审核'
        }
        return restatus
      },
      /**
       * 提交审核*
       * */
      commit(row) {
        getByKey('assets_stock_allot').then(response => {
          this.instanceId = response.data.id
          commit(row.aId, this.instanceId).then(response => {
            this.msgSuccess('ok')
            this.getList()
          })
        })
      },
      remoiit() {
        this.$refs['form'].validate(valid => {
          if (valid) {
            recommit(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess('修改成功')
                this.open = false
                this.getList()
              } else {
                this.msgError(response.msg)
              }
            })
          }
        })
      },
      /*
     *显示流程表单
     * */
      showForms(index, row) {
        this.hforms.open = false
        this.hforms.open = true
        this.hforms.title = '查看审核流程'
        this.$nextTick(() => {
          this.$refs.addEnterprise.showForms(row.instanceId)
        })
      },
      showImage(index, row) {
        let instanceId = row.instanceId
        instanceId = process.env.VUE_APP_BASE_API + '/leaveNew/read-resource?processInstanceId=' + instanceId + '&t=' + Math.random()
        this.activitiImg.open = true
        this.activitiImg.src = instanceId
      },
      /** 再次提交审核*/
      recommit(row) {
        this.reset()
        const aId = row.aId || this.ids
        getAllot(aId).then(response => {
          this.form = response.data
          let depOutId = this.form.depOutId
          selectlist(depOutId).then(response => {
            this.userOptions = response.data
            this.outlistStock(depOutId, '', 0)
          })
          let depId = this.form.depId
          selectlist(depId).then(response => {
            this.userAllotOptions = response.data
          })
          this.form.leadOutUserId = this.form.leadOutUserId + ''
          this.form.leadUserId = this.form.leadUserId + ''
          this.form.taskId = row.taskId
          this.open = true
          this.title = '修改资产调拨'
        })
      },
      processDefinitionKey() {
        getByKey('assets_stock_allot').then(response => {
          this.instanceId = response.data.id
          console.log(this.instanceId)
        })
      }
    },
    watch: {
      'form.depOutId': function(newVal) {
        console.log(newVal)
        if (newVal == undefined) {
          console.log(newVal)
          this.form.stockValue = []
          this.form.leadOutUserId = undefined
          this.userOptions = []
        }
      },
      'form.depId': function(newVal) {
        console.log(newVal)
        if (newVal == undefined) {
          console.log(newVal)
          this.form.leadUserId = undefined
          this.userAllotOptions = []
        }
      }
    }
  }
</script>
<style rel="stylesheet/scss" lang="scss">
  .demo-table-expand {
    font-size: 0;
  }

  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }

  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
</style>

