<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="报废类型" prop="scrapType">
        <el-select v-model="queryParams.scrapType" placeholder="请选择报废类型" clearable size="small">
          <el-option
            v-for="dict in scrapTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="资产类型" prop="dbMaterielId">
        <el-input maxlength="20"
                  v-model="queryParams.dbMaterielId"
                  placeholder="请输入资产类型"
                  clearable
                  size="small"
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="供应商名称" prop="dbSupplierName">
        <el-input maxlength="20"
                  v-model="queryParams.dbSupplierName"
                  placeholder="请输入供应商名称"
                  clearable
                  size="small"
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="资产名称" prop="dbAsStName">
        <el-input maxlength="20"
                  v-model="queryParams.dbAsStName"
                  placeholder="请输入资产名称"
                  clearable
                  size="small"
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="资产编号" prop="dbAsStNumber">
        <el-input maxlength="20"
                  v-model="queryParams.dbAsStNumber"
                  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:scrap: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:scrap: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:scrap: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:scrap:export']"-->
      <!--        >导出-->
      <!--        </el-button>-->
      <!--      </el-col>-->
    </el-row>

    <el-table v-loading="loading" :data="scrapList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="报废类型" align="center" prop="scrapType" :formatter="scrapTypeFormat"/>
      <el-table-column label="供应商名称" align="center" prop="dbSupplierName"/>
      <el-table-column label="资产名称" align="center" prop="dbAsStName"/>
      <el-table-column label="资产编号" align="center" prop="dbAsStNumber"/>
      <el-table-column label="报废时间" align="center" prop="scrapTime" width="180">
        <template slot-scope="scope">
          <span>{{ formDate(scope.row.scrapTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="处理人" align="center" prop="scrapUser"/>
      <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:scrap:edit']"
            >提交审核
            </el-button>
            <el-button
              type="success"
              icon="el-icon-edit"
              size="small"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['assets:scrap:edit']"
            >修改
            </el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="small"
              @click="handleDelete(scope.row)"
              v-hasPermi="['assets:scrap: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:scrap: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="scrapType">
              <el-select v-model="form.scrapType" placeholder="请选择报废类型">
                <el-option
                  v-for="dict in scrapTypeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报废时间" prop="scrapTime">
              <!--              <el-date-picker clearable size="small"-->
              <!--                              v-model="form.scrapTime"-->
              <!--                              type="date"-->
              <!--                              value-format="yyyy-MM-dd"-->
              <!--                              placeholder="选择报废时间">-->
              <!--              </el-date-picker>-->
              <el-date-picker clearable size="small" style="width: 200px"
                              v-model="form.scrapTime"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="选择报废时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="处理部门" prop="depName">
              <el-input maxlength="20" v-model="form.depName" placeholder="请输入处理部门" :disabled="true"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="处理人" prop="scrapUser">
              <el-input maxlength="20" v-model="form.scrapUser" placeholder="请输入处理人" :disabled="true"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="资产类型" prop="dbMaterielId">
              <treeselect
                v-model="form.dbMaterielId"
                :options="treeOptions"
                :show-count="true" @select="selectDepart"
                placeholder="选择上级菜单"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <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-col>
        </el-row>


        <el-form-item label="资产编号" prop="dbAsStNumber">
          <el-input maxlength="20" v-model="form.dbAsStNumber" placeholder="请输入资产编号" :disabled="true"/>
        </el-form-item>
        <el-form-item label="供应商" prop="dbSupplierName">
          <el-input maxlength="20" v-model="form.dbSupplierName" placeholder="请输入供应商名称" :disabled="true"/>
        </el-form-item>
        <el-form-item label="报废原因" prop="scrapReason">
          <el-input maxlength="200" type="textarea" v-model="form.scrapReason" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <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>
      </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 {
    listScrap,
    getScrap,
    delScrap,
    addScrap,
    commit,
    recommit,
    updateScrap,
    exportScrap
  } from '@/api/assets/scrap'
  import { selectlistStock, selectStockDictLabel } from '@/api/assets/stock'
  import { treelist } from '@/api/system/materiel'

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

  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: 'Scrap',
    components: {
      Treeselect,
      addEnterprise
    },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 资产报废表格数据
        scrapList: [],
        // 弹出层标题
        title: '',
        // 是否显示弹出层
        open: false,
        // 报废类型字典
        scrapTypeOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          scrapType: undefined,
          dbMaterielId: undefined,
          dbSupplierId: undefined,
          dbSupplierName: undefined,
          dbAsStId: undefined,
          dbAsStName: undefined,
          dbAsStNumber: undefined,
          scrapTime: undefined,
          depId: undefined,
          depName: undefined,
          scrapReason: undefined,
          scrapUserId: undefined,
          scrapUser: undefined,
          instanceId: undefined,
          state: undefined
        },
        // 表单参数
        form: {},
        treeOptions: [],
        stockOption: [],
        // 表单校验
        rules: {
          scrapType: [
            { required: true, message: '报废类型不能为空', trigger: 'blur' }
          ],
          scrapTime: [
            { required: true, message: '报废时间不能为空', trigger: 'blur' }
          ],
          dbMaterielId: [
            { required: true, message: '资产类型不能为空', trigger: 'blur' }
          ],
          dbSupplierId: [
            { required: true, message: '供应商id不能为空', trigger: 'blur' }
          ],
          dbAsStId: [
            { required: true, message: '资产id不能为空', trigger: 'blur' }
          ],
          depId: [
            { required: true, message: '处理部门id不能为空', trigger: 'blur' }
          ],
          scrapUserId: [
            { required: true, message: '处理人id不能为空', trigger: 'blur' }
          ]
        },
        user: {
          id: undefined,
          name: undefined,
          deptId: undefined,
          deptName: undefined
        },
        hforms: {
          title: '查看审核流程',
          open: false,
          data: []
        },
        activitiImg: {
          title: '查看审核流程图',
          open: false,
          src: ''
        },
        instanceId: ''
      }
    },
    created() {
      this.getList()
      this.processDefinitionKey()
      this.getDicts('scrap_type').then(response => {
        this.scrapTypeOptions = response.data
      })
      this.getSysUser()
      this.treelist()
    },
    methods: {
      /** 查询资产报废列表 */
      getList() {
        this.loading = true
        listScrap(this.queryParams).then(response => {
          this.scrapList = response.rows
          this.total = response.total
          this.loading = false
        })
      },
      // 报废类型字典翻译
      scrapTypeFormat(row, column) {
        return this.selectDictLabel(this.scrapTypeOptions, row.scrapType)
      },
      // 取消按钮
      cancel() {
        this.open = false
        this.reset()
      },
      // 表单重置
      reset() {
        this.form = {
          aId: undefined,
          scrapType: undefined,
          dbMaterielId: undefined,
          dbSupplierId: undefined,
          dbSupplierName: undefined,
          dbAsStId: undefined,
          dbAsStName: undefined,
          dbAsStNumber: undefined,
          scrapTime: undefined,
          depId: undefined,
          depName: undefined,
          scrapReason: undefined,
          scrapUserId: undefined,
          scrapUser: undefined,
          remark: undefined,
          instanceId: undefined,
          taskId: undefined,
          state: undefined,
          createBy: undefined,
          createTime: undefined,
          updateBy: undefined,
          updateTime: undefined
        }
        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.form.depId = this.user.deptId
        this.form.depName = this.user.deptName
        this.form.scrapUserId = this.user.id
        this.form.scrapUser = this.user.name
        this.open = true
        this.title = '添加资产报废'
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset()
        const aId = row.aId || this.ids
        getScrap(aId).then(response => {
          this.form = response.data
          selectlistStock(this.form.dbMaterielId).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) {
              updateScrap(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess('修改成功')
                  this.open = false
                  this.getList()
                } else {
                  this.msgError(response.msg)
                }
              })
            } else {
              addScrap(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 delScrap(aIds)
        }).then(() => {
          this.getList()
          this.msgSuccess('删除成功')
        }).catch(function() {
        })
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams
        this.$confirm('是否确认导出所有资产报废数据项?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function() {
          return exportScrap(queryParams)
        }).then(response => {
          this.download(response.msg)
        }).catch(function() {
        })
      },
      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)
        })
      },
      treelist() {
        treelist().then(response => {
          this.treeOptions = response.data
        })
      },
      // 获取当前选中部门的名称
      selectDepart(val) {
        let dbMaterielId = val.id
        this.stockOption = []
        this.form.dbAsStId = undefined
        this.selectlistStock(dbMaterielId)
      },
      selectlistStock(dbMaterielId) {
        selectlistStock(dbMaterielId, 1).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
        //供应商id
        this.form.dbSupplierId = obj.sId
        //供应商id
        this.form.dbSupplierName = obj.sName

        //console.log(this.form)
      },
      /** 再次提交审核*/
      recommit(row) {
        this.reset()
        const aId = row.aId || this.ids
        getScrap(aId).then(response => {
          this.form = response.data
          this.form.taskId = row.taskId
          this.selectlistStock(this.form.dbMaterielId)
          this.open = true
          this.title = '修改资产出库'
        })
      },
      processDefinitionKey() {
        getByKey('assets_stock_scrap').then(response => {
          this.instanceId = response.data.id
          console.log(this.instanceId)
        })
      },
      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_scrap').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
      }
    }
  }
</script>
