<template>
  <div class="app-container">
    <div v-show="isXuanche === false">
      <!--标题按钮部分开始-->
      <div class="tab-header webtop">
        <!--标题-->
        <div>{{ viewTitle }}</div>
        <!--start 添加修改按钮-->
        <div>
          <el-button
            type="primary"
            size="small"
            :disabled="submitdisabled"
            @click="saveEdit()"
          >保存
          </el-button>
          <el-button type="primary" size="small"   @click="handleSubmit()">提交
          </el-button>
          <el-button type="danger" @click="openStop">终 止</el-button>
        </div>
        <!--end 添加修改按钮-->
        <!--end 详情按钮-->
      </div>
      <!--标题按钮部分结束-->
      <!--Start 新增修改部分-->
      <div class="listconadd"><!-- -->
        <div class="title">车辆采购退库申请</div> <!--:rules="rules"-->
        <el-form ref="form_obj" :model="formobj" :rules="rules" :inline="true" label-width="120px">
          <div>
            <!--第一行-->
            <el-row>
              <el-col :span="8">
                <el-form-item label="申请编号:">{{ formobj.applicationCode }}</el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="申请人:">{{ formobj.name }}</el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="申请日期:">{{ formobj.createTime }}</el-form-item>
              </el-col>
            </el-row>
          </div>
          <div class="invoiceadd" style="margin-top: 5px;">
            <el-row>
              <el-col :span="12">
                <el-form-item prop="reason" label="退库原因">
                  <el-input
                    v-model="formobj.reason"
                    placeholder="请输入验收员"
                    class="addinputw"
                    clearable
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item prop="money" label="费用">
                  <el-input
                    v-model="formobj.money"
                    placeholder="请输入费用"
                    class="addinputw"
                    clearable
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <div class="addtable">
            <div class="tabletitle">
              <div class="titlename">
                货物明细
              </div>
              <el-button size="medium" type="primary" @click="handleyudingcheliang" class="btntopbluebut">选择车辆
              </el-button>
            </div>
            <template class="tablelist">
              <el-table :data="list" border style="width: 100%" :index="index">
                <el-table-column align="center" label="序号" type="index" width="50"/>
                <el-table-column label="操作" align="center" width="250px" class-name="small-padding fixed-width">
                  <template slot-scope="scope">
                    <el-button size="mini" type="danger"
                               @click="dataDelete(scope.row,scope.$index,list[scope.$index])">删除
                    </el-button>
                  </template>
                </el-table-column>
                <el-table-column label="车架号" align="center">
                  <template slot-scope="scope" @click="">
                    <span>{{scope.row.vinNo}}</span>
                  </template>
                </el-table-column>
                <el-table-column label="车型名称" align="center">
                  <template slot-scope="scope">
                    <span>{{scope.row.modelName}}</span>
                  </template>
                </el-table-column>
                <el-table-column label="常用配置" align="center">
                  <template slot-scope="scope">
                    <span>{{scope.row.configName}}</span>
                  </template>
                </el-table-column>
                <el-table-column label="入库时间" align="center">
                  <template slot-scope="scope">
                    <span>{{scope.row.inboundDate}}</span>
                  </template>
                </el-table-column>
              </el-table>
            </template>
          </div>
        </el-form>
      </div>
      <!--End 添加修改部分-->
    </div>
    <xuanzecheliang ref="xuanChe" v-show="isXuanche === true" @handleVehicle="selectVehicle"
                    @doback="resetState"></xuanzecheliang>
  </div>
</template>

<script>
  import req from '@/api/supplychain/purchasereturntowarehouse'
  import request from '@/api/flow/vehicleReturn'
  import xuanzecheliang from '../../supplychain/caigoutuiku/relation/xuanzecheliang.vue'

  export default {
    name: 'caigoutuikuEdit',
    components: {
      xuanzecheliang
    },
    data() {
      return {
        isXuanche: false,
        viewTitle: '',
        dialogStatus: '',
        index: 0,
        list: [],
        obj: {},
        // 表单数据
        formobj: {
          sid: '', // 一条数据的sid
          applicationCode: '',
          name: '',
          createTime: '',
          userSid: '', // 用户人sid
          detailsList: [],
          businessSid: '',
          comment: '',
          instanceId: '',
          taskId: '',
          taskDefKey:'',
          taskName:''
        },
        stopList: { // 终止列表
          businessSid: '',
          comment: '',
          instanceId: '',
          taskId: '',
          userSid: '' // window.sessionStorage.getItem('userSid')
        },
        rules: {},
        submitdisabled: false, // 保存按钮
        disabled: false // 提交按钮
      }
    },
    created() {
      var one = window.location.href.indexOf('&data') + 6
      const data = window.location.href.substr(one) // url解码unescape()已从web中移除,尽量不使用
      const obj = JSON.parse(decodeURIComponent(data))
      this.obj=obj;
      // ===获取sid
      console.log('iframe页面获取到的url:' + window.location.href)
      this.showEdit(obj.businessSid)
      // ===获取参数
      // 终止列表
      this.stopList.businessSid = obj.businessSid
      this.stopList.instanceId = obj.instanceId
      this.stopList.taskId = obj.taskId
      this.stopList.userSid = obj.userSid
      window.parent.postMessage({
        cmd: 'returnHeight',
        params: {
          //告诉父级页面，子页面的弹框高度。
          code: 2,
          data: 600 + 'px'
        }
      }, '*')
    },
    methods: {
      init() {

      },
      // 明细表添加一行数据
      handleyudingcheliang() {
        this.isXuanche = true
        const vinNoList = []
        this.list.forEach(element => {
          vinNoList.push(element.vinNo)
        })
        this.$refs['xuanChe'].loadVinNo()
      },
      resetState() {
        this.isXuanche = false
      },
      selectVehicle(depositVehicleList) {
        for (var i = 0; i < depositVehicleList.length; i++) {
          this.list.push({
            configName: depositVehicleList[i].configName,
            inboundDate: depositVehicleList[i].priceDate,
            modelName: depositVehicleList[i].vehicleAlias,
            vinNo: depositVehicleList[i].vinNo
          })
        }
        console.log('车辆表数据', this.list)
      },
      // 明细表删除一行数据
      dataDelete(index, row) {
        this.list.splice(index, 1)
      },

      showEdit(sid, nodeState) {
        this.$nextTick(() => {
          this.$refs['form_obj'].clearValidate()
        })
        this.dialogStatus = 'edit'
        this.viewTitle = '【编辑】车辆采购退库申请'
        req.detailsInfo({
          sid: sid
        }).then(resp => {
          const data = resp.data
          this.formobj = data
          this.formobj.sid=this.obj.businessSid
          this.list = data.voList
          // ---修改名称 先把temp对象转化成json字符串做替换字符串操作，再转化成temp对象---
          this.formobj = JSON.parse(JSON.stringify(this.formobj).replace(/voList/g, 'detailsList')
          )
          console.log('编辑初始化', this.formobj)
        }).catch(e => {
          this.submitdisabled = false
        })
        if (nodeState == '' || nodeState == '发起订单') {
          this.disabled = false
        } else {
          this.disabled = true
        }
      },
      // 终止
      openStop() {
        this.$confirm('是否确认执行终止操作', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.handleStop()
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消终止'
            })
          })
      },
      /** 终止任务 */
      handleStop() {
        this.stopList.comment = this.comment
        request.breakTask(this.stopList).then((response) => {
          if (response.code === '200') {
            this.$notify({
              title: '提示',
              message: '执行成功',
              type: 'success',
              duration: 2000
            })
            // this.refreshIt()
          } else {
            this.$notify({
              title: '提示',
              message: '执行失败',
              type: 'error',
              duration: 2000
            })
          }
        })
      },
      saveEdit() {
        const _this = this
        this.$refs['form_obj'].validate(valid => {
          if (valid) {
            this.submitdisabled = true
            req.save(this.formobj).then(resp => {
              this.submitdisabled = false
              if (resp.success) {
                _this.handleReturn('true')
              }
            }).catch(() => {
              this.submitdisabled = false
            })
          } else {
            return false
          }
        })
      },
      handleSubmit() {
        this.submitdisabled = true
        this.formobj.userSid = window.sessionStorage.getItem('userSid')
        this.formobj.orgSid = this.$store.getters.orgSid
        this.formobj.businessSid = this.obj.businessSid
        this.formobj.taskId = this.obj.taskId
        const _this = this
        this.$refs['form_obj'].validate(valid => {
          if (valid) {
            this.submitdisabled = true
            req.submitVehicleReturn(this.formobj).then(resp => {
              this.submitdisabled = false
              if (resp.success) {
                _this.handleReturn('true')
              }
            }).catch(() => {
              this.submitdisabled = false
            })
          } else {
            return false
          }
        })
      }
    }
  }
</script>

<style scoped>
  .title {
    padding: 28px 0;
  }
</style>
