<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="出库类型" prop="stockType">
        <el-select v-model="queryParams.stockType" placeholder="请选择出库类型" clearable size="small">
          <el-option
            v-for="dict in stockTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="出库时间" prop="stockOutTime">
        <el-date-picker clearable size="small" style="width: 200px"
                        v-model="queryParams.stockOutTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择出库时间">
        </el-date-picker>
      </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:out: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:out: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:out: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:out:export']"
        >导出
        </el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="outList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="资产名称" align="center" prop="dbAsStName"/>
      <el-table-column label="资产编号" align="center" prop="dbAsStNumber"/>
      <el-table-column label="出库类型" align="center" prop="stockType" :formatter="stockTypeFormat"/>
      <el-table-column label="出库时间" align="center" prop="stockOutTime" width="180">
        <template slot-scope="scope">
          <span>{{ formDate(scope.row.stockOutTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="领用部门名称" align="center" prop="depName"/>
      <el-table-column label="领用人" align="center" prop="leadUser"/>
      <el-table-column label="状态" align="center" prop="state" :formatter="statusFormat"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180"/>
      <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:out:edit']"
            >修改
            </el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="small"
              @click="handleDelete(scope.row)"
              v-hasPermi="['assets:out: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:out: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="700px" :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="出库类型" prop="stockType">
          <el-select v-model="form.stockType" placeholder="请选择出库类型">
            <el-option
              v-for="dict in stockTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="出库时间" prop="stockOutTime">
          <el-date-picker clearable size="small" style="width: 200px"
                          v-model="form.stockOutTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择出库时间">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="领用部门" prop="depName">
          <el-input v-model="form.depName" placeholder="请输入领用部门名称" :disabled="true"/>
        </el-form-item>

        <el-form-item label="领用人" prop="leadUser">
          <el-input v-model="form.leadUser" placeholder="请输入领用人" :disabled="true"/>
        </el-form-item>
        <el-form-item label="资产类型" prop="dbMaterielId">
          <treeselect
            v-model="form.dbMaterielId"
            :options="treeOptions"
            :show-count="true" @select="selectDepart"
            placeholder="选择上级菜单"
          />
        </el-form-item>
        <el-form-item label="资产" prop="dbAsStId">
          <el-select v-model="form.dbAsStId" placeholder="请选择资产" @change="setData">
            <el-option
              v-for="dict in stockOption"
              :key="dict.aId"
              :label="dict.aNumber+'-'+dict.aName"
              :value="dict.aId"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="资产编号">
          <el-input v-model="form.dbAsStNumber" placeholder="请输入备注" :disabled="true"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input maxlength="200" type="textarea" v-model="form.remark" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <template>
          <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>
        </template>
      </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 { listOut, getOut, delOut, addOut, commit, recommit, updateOut, exportOut } from '@/api/assets/out'

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

  import { selectlistStock, selectStockDictLabel } from '@/api/assets/stock'

  import { treelist } from '@/api/system/materiel'

  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: 'Out',
    components: {
      Treeselect, addEnterprise
    },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 资产出库表格数据
        outList: [],
        // 弹出层标题
        title: '',
        // 是否显示弹出层
        open: false,
        // 出库类型字典
        stockTypeOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          stockType: undefined,
          stockOutTime: undefined,
          depId: undefined,
          depName: undefined,
          leadUserId: undefined,
          leadUser: undefined,
          dbMaterielId: undefined,
          dbAsStId: undefined,
          dbAsStName: undefined,
          dbAsStNumber: undefined,
          instanceId: undefined,
          state: undefined
        },
        // 表单参数
        form: {},
        user: {
          id: undefined,
          name: undefined,
          deptId: undefined,
          deptName: undefined
        },
        stockOption: [],
        treeOptions: [],

        hforms: {
          title: '查看审核流程',
          open: false,
          data: []
        },
        activitiImg: {
          title: '查看审核流程图',
          open: false,
          src: ''
        },
        instanceId: '',
        // 表单校验
        rules: {
          stockType: [
            { required: true, message: '出库类型不能为空', trigger: 'blur' }
          ],
          stockOutTime: [
            { required: true, message: '出库时间不能为空', trigger: 'blur' }
          ],
          dbAsStId: [
            { required: true, message: '资产id不能为空', trigger: 'blur' }
          ],
          dbMaterielId: [
            { required: true, message: '资产类型不能为空', trigger: 'blur' }
          ],
          dbAsStName: [
            { required: true, message: '资产名称不能为空', trigger: 'blur' }
          ]

        }
      }
    },
    created() {
      this.processDefinitionKey()
      this.getList()
      this.getDicts('stock_type').then(response => {
        this.stockTypeOptions = response.data
      })
      this.getSysUser()
      this.treelist()
    },
    methods: {
      treelist() {
        treelist().then(response => {
          this.treeOptions = response.data
        })
      },
      /** 查询资产出库列表 */
      getList() {
        this.loading = true
        listOut(this.queryParams).then(response => {
          this.outList = response.rows
          this.total = response.total
          this.loading = false
        })
      },
      // 获取当前选中部门的名称
      selectDepart(val) {
        let dbMaterielId = val.id
        this.stockOption = []
        this.form.dbAsStId = undefined
        selectlistStock(dbMaterielId, 0).then(response => {
          this.stockOption = response.data
          console.log(this.stockOption)
        })
      },
      selectlistStock(dbMaterielId) {
        selectlistStock(dbMaterielId).then(response => {
          this.stockOption = response.data
          console.log(this.stockOption)
        })
      },
      setData(val) {
        console.log(val)
        var obj = selectStockDictLabel(this.stockOption, val)
        console.log(obj)
        this.form.dbAsStName = obj.aName
        this.form.dbAsStNumber = obj.aNumber
        //console.log(this.form)
      },

      // 出库类型字典翻译
      stockTypeFormat(row, column) {
        return this.selectDictLabel(this.stockTypeOptions, row.stockType)
      },
      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
      },
      // 取消按钮
      cancel() {
        this.open = false
        this.reset()
      },
      // 表单重置
      reset() {
        this.form = {
          aId: undefined,
          stockType: undefined,
          stockOutTime: undefined,
          depId: undefined,
          depName: undefined,
          leadUserId: undefined,
          leadUser: undefined,
          dbMaterielId: undefined,
          dbAsStId: undefined,
          dbAsStName: undefined,
          dbAsStNumber: undefined,
          remark: undefined,
          instanceId: undefined,
          taskId: undefined,
          state: undefined,
          createBy: undefined,
          createTime: undefined,
          updateBy: undefined,
          updateTime: undefined
        }
        this.resetForm('form')
      },
      getSysUser() {
        getUserProfile().then(response => {
          let data = response.data
          this.user.id = data.userId
          this.user.name = data.userName
          this.user.deptId = data.dept.deptId
          this.user.deptName = data.dept.deptName
          console.log(this.user)
        })
      },
      /** 搜索按钮操作 */
      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.form.depId = this.user.deptId
        this.form.depName = this.user.deptName
        this.form.leadUserId = this.user.id
        this.form.leadUser = this.user.name
        this.open = true
        this.title = '添加资产出库'
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset()
        const aId = row.aId || this.ids
        getOut(aId).then(response => {
          this.form = response.data
          selectlistStock(this.form.dbMaterielId, 0).then(response => {
            this.stockOption = response.data
            var datas = this.stockOption
            var value = this.form.dbAsStId
            var key = 'aId'
            if (!this.containData(datas, key, value)) {
              this.form.dbAsStId = undefined
            }
          })
          this.open = true
          this.title = '修改资产出库'
        })
      },
      /** 提交按钮 */
      submitForm: function() {
        this.$refs['form'].validate(valid => {
          if (valid) {
            if (this.form.aId != undefined) {
              updateOut(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess('修改成功')
                  this.open = false
                  this.getList()
                } else {
                  this.msgError(response.msg)
                }
              })
            } else {
              console.log(this.form)
              addOut(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 delOut(aIds)
        }).then(() => {
          this.getList()
          this.msgSuccess('删除成功')
        }).catch(function() {
        })
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams
        this.$confirm('是否确认导出所有资产出库数据项?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function() {
          return exportOut(queryParams)
        }).then(response => {
          this.download(response.msg)
        }).catch(function() {
        })
      },

      /**
       * 提交审核*
       * */
      commit(row) {
        getByKey('assets_stock_out').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
        getOut(aId).then(response => {
          this.form = response.data
          this.form.taskId = row.taskId
          selectlistStock(this.form.dbMaterielId, 0).then(response => {
            this.stockOption = response.data
            var datas = this.stockOption
            var value = this.form.dbAsStId
            var key = 'aId'
            if (!this.containData(datas, key, value)) {
              this.form.dbAsStId = undefined
            }
          })
          this.open = true
          this.title = '修改资产出库'
        })
      },
      processDefinitionKey() {
        getByKey('assets_stock_out').then(response => {
          this.instanceId = response.data.id
          console.log(this.instanceId)
        })
      }
    }
  }
</script>
