<template>
  <div class="app-container">
    <div v-show="isXuanche === false">
      <!--标题按钮部分开始-->
      <div class="tab-header webtop">
        <!--标题-->
        <div>【编辑】分公司间调账申请</div>
        <!--start 添加修改按钮-->
        <div>
          <el-button
            type="primary"
            size="small"
            :disabled="submitdisabled"
            @click="handleCreate()"
          >保存
          </el-button>
          <el-button type="primary" size="small" :disabled="submitdisabled" @click="handleSubmit()">提交
          </el-button>
        </div>
        <!--end 添加修改按钮-->
        <!--end 详情按钮-->
      </div>
      <!--标题按钮部分结束-->
      <!--Start 新增修改部分-->
      <div class=""><!-- -->
        <div class="title">分公司间调账申请</div> <!--:rules="rules"-->
        <el-form ref="dataForm" :model="temp" :rules="rules" :inline="true" label-width="120px">
          <div class="invoiceadd" style="margin-top: 5px;">
            <el-row>
              <el-col :span="8">
                <el-form-item prop="reason" label="调账类型">
                  <el-select v-model="temp.accadjTypeKey" placeholder="请选择" clearable class="addinputw"
                             @change="accadjTypeKeyChange"
                             :disabled="dialogStatus == 'edit'">
                    <el-option v-for="item in accadjType_list" :key="item.dictKey" :label="item.dictValue"
                               :value="item.dictKey"/>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8"><!-- :readonly="vehicleList[scope.$index].inboundDate" -->
                <el-form-item prop="money" label="调出分公司">
                  <el-select v-model="temp.callOutOrgSid" placeholder="请选择" clearable class="addinputw"
                             :disabled="temp.accadjTypeKey == '02' || dialogStatus == 'edit'"
                             @change="callOutOrgSidChange">
                    <el-option v-for="item in useOrg_list" :key="item.sid" :label="item.name"
                               :value="item.sid"/>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item prop="money" label="调入分公司">
                  <el-select v-model="temp.callInOrgSid" placeholder="请选择" clearable class="addinputw"
                             :disabled="temp.accadjTypeKey == '01' || dialogStatus == 'edit'"
                             @change="callInOrgSidChange">
                    <el-option v-for="item in useOrg_list" :key="item.sid" :label="item.name"
                               :value="item.sid"/>
                  </el-select>
                </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="handletiaozhangcheliang" class="btntopbluebut">选择车辆
              </el-button>
            </div>
            <template class="tablelist">
              <el-table :data="list" border style="width: 100%" :index="index">
                <el-table-column align="center" fixed label="序号" type="index" width="50"/>
                <el-table-column label="操作" fixed align="center" width="80" 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" width="190">
                  <template slot-scope="scope">
                    <span>{{ scope.row.vehicleAlias }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="常用配置" align="center" width="360">
                  <template slot-scope="scope">
                    <span>{{ scope.row.configName }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="车架号" align="center" width="120">
                  <template slot-scope="scope" @click="">
                    <span>{{ scope.row.vinNo }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="库存地点" align="center" width="200">
                  <template slot-scope="scope" @click="">
                    <span>{{ scope.row.inventoryLocationName }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="内销价格" align="center" width="90">
                  <template slot-scope="scope">
                    <span>{{ scope.row.witPinMoney }}</span>
                  </template>
                </el-table-column>
<!--                <el-table-column label="发票类型" align="center" width="140">-->
<!--                  <template slot-scope="scope">-->
<!--                    &lt;!&ndash;                    <el-input v-model="scope.row.invoiceTypeValue" placeholder="请输入" class="addinputw"&ndash;&gt;-->
<!--                    &lt;!&ndash;                              :readonly="vehicleList[scope.$index].inboundDate"/>&ndash;&gt;-->
<!--                    <span>{{ scope.row.invoiceTypeValue }}</span>-->
<!--                  </template>-->
<!--                </el-table-column>-->
                <el-table-column label="运费" align="center" width="90">
                  <template slot-scope="scope">
                    <span>{{ scope.row.freight }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="运费承担方" align="center" width="120">
                  <template slot-scope="scope">
                    <span>{{ scope.row.freightUndertakerName }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="备注" align="left" header-align="center" width="300">
                  <template slot-scope="scope">
                    <span>{{ scope.row.remarks }}</span>
                  </template>
                </el-table-column>
              </el-table>
            </template>
          </div>
        </el-form>
      </div>
      <!--End 添加修改部分-->
    </div>
    <tiaozhangcheliang-list ref="xuanChe" v-show="isXuanche === true" @handleVehicle="selectVehicle"
                            @doback="resetState"/>
  </div>
</template>

<script>
import tiaozhangcheliangList from '@/views/supplychain/tiaozhangshenqingguanli/relation/tiaozhangcheliangList'
import { fetchDetailsBySid, save, submitAccAdjApply } from '@/api/supplychain/tiaozhangshenqing.js'
import { getOrg, getPathSidByUserSid } from '@/api/cheliang/basevehiclemodel'
import { typeValues } from '@/api/cheliang/dictcommons'

export default {
  name: 'tiaozhangshenqingEdit',
  components:{
    tiaozhangcheliangList
  },
  data() {
    return {
      isXuanche: false,
      viewTitle: '',
      dialogStatus: '',
      index: 0,
      list: [],
      vehicleList: [],
      useOrg: '',
      accadjType_list: [],
      useOrg_list: [],
      // 表单数据
      temp: {
        sid: '',
        createBySid: '', // 创建人sid
        applyDate: '', // 申请日期
        accadjTypeKey: '', // 调账类型key
        accadjTypeValue: '', // 调账类型value
        callOutOrgSid: '', // 调出分公司sid
        callOutOrgName: '', // 调出分公司名称
        callInOrgSid: '', // 调入分公司sid
        callInOrgName: '', // 调入分公司名称
        useOrgSid: '', // 使用组织sid
        createOrgSid: '', // 创建组织sid
        nodeState: '', // 流程状态
        accSids: [] // 调账车辆类型sid
      },
      rules: {

      },
      submitdisabled: false, // 保存按钮
      disabled: false // 提交按钮
    }
  },
  mounted() {
    window.parent.postMessage({
      cmd: 'returnHeight',
      params: {
        // 告诉父级页面，子页面的弹框高度。
        code: 2,
        data: document.body.scrollHeight + 120 + 'px'
      }
    }, '*')
  },
  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.showEdit(obj.businessSid,obj.instanceId,obj.taskId)
  },
  methods: {
    // 输入数字正则
    oninput(val, limit = 0) {
      val = val.replace(/[^\d.]/g, '') //保留数字
      val = val.replace(/^00/, '0.') //开头不能有两个0
      val = val.replace(/^\./g, '0.') //开头为小数点转换为0.
      val = val.replace(/\.{2,}/g, '.') //两个以上的小数点转换成一个
      val = val.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.'); //只保留一个小数点
      /^0\d+/.test(val) ? val = val.slice(1) : '' //两位以上数字开头不能为0
      const str = '^(\\d+)\\.(\\d{' + limit + '}).*$'
      const reg = new RegExp(str)
      if (limit === 0) {
        // 不需要小数点
        val = val.replace(reg, '$1')
      } else {
        // 通过正则保留小数点后指定的位数
        val = val.replace(reg, '$1.$2')
      }
      return val
    },
    // 根据登陆人sid查询分公司
    getPathSid() {
      const userSid = window.sessionStorage.getItem('userSid')
      getPathSidByUserSid({ userSid: userSid }).then((res) => {
        if (res.code === '200') {
          this.useOrg = res.data
          this.temp.createOrgSid = res.data
        }
      })
    },
    getType() {
      typeValues({
        type: 'accadjType'
      }).then((response) => {
        if (response.code === '200' && response.data) {
          this.accadjType_list = response.data
        }
      })
    },
    getListOrgAll() {
      getOrg().then((res) => {
        if (res.success) {
          this.useOrg_list = res.data
        }
      })
    },
    accadjTypeKeyChange(val) {
      if (val) {
        const choosetItem = this.accadjType_list.filter((item) => item.dictKey == val)
        this.temp.accadjTypeValue = choosetItem[0].dictValue
        console.log('name:', this.temp.accadjTypeValue, 'key:', this.temp.accadjTypeKey)
        // 调入
        if (this.temp.accadjTypeKey == '01') {
          this.temp.callInOrgSid = this.useOrg
          const name = this.useOrg_list.filter((item) => item.sid == this.temp.callInOrgSid)
          this.temp.callInOrgName = name[0].name
          console.log('name:', this.temp.callInOrgName, 'sid:', this.temp.callInOrgSid)
          this.temp.callOutOrgName = ''
          this.temp.callOutOrgSid = ''
        }
        // 调出
        if (this.temp.accadjTypeKey == '02') {
          this.temp.callOutOrgSid = this.useOrg
          const name = this.useOrg_list.filter((item) => item.sid == this.temp.callOutOrgSid)
          this.temp.callOutOrgName = name[0].name
          console.log('name:', this.temp.callOutOrgName, 'sid:', this.temp.callOutOrgSid)
          this.temp.callInOrgName = ''
          this.temp.callInOrgSid = ''
        }
      }
    },
    callOutOrgSidChange(val) {
      const choosetItem = this.useOrg_list.filter((item) => item.sid == val)
      this.temp.callOutOrgName = choosetItem[0].name
      console.log('name:', this.temp.callOutOrgName, 'key:', this.temp.callOutOrgSid)
    },
    callInOrgSidChange(val) {
      const choosetItem = this.useOrg_list.filter((item) => item.sid == val)
      this.temp.callInOrgName = choosetItem[0].name
      console.log('name:', this.temp.callInOrgName, 'key:', this.temp.callInOrgSid)
    },
    handletiaozhangcheliang() {
      if (this.temp.accadjTypeKey == '') {
        this.$message({
          showClose: true,
          message: '请选择调账类型',
          type: 'error'
        })
        return
      }
      if (this.temp.callOutOrgSid == '') {
        this.$message({
          showClose: true,
          message: '请选择调出分公司',
          type: 'error'
        })
        return
      }
      if (this.temp.callInOrgSid == '') {
        this.$message({
          showClose: true,
          message: '请选择调入分公司',
          type: 'error'
        })
        return
      }
      this.isXuanche = true
      const vinNoList = []
      this.list.forEach(element => {
        vinNoList.push(element.sid)
      })
      this.$refs['xuanChe'].showCheList(this.temp.accadjTypeKey, this.temp.callOutOrgSid, this.temp.callInOrgSid, vinNoList)
    },
    resetState() {
      this.isXuanche = false
    },
    // 明细表添加一行数据
    selectVehicle(vehicleList) {
      console.log('vehicleList', vehicleList)
      this.vehicleList = vehicleList
      for (var i = 0; i < vehicleList.length; i++) {
        this.list.push({
          sid: vehicleList[i].sid,
          vinNo: vehicleList[i].vinNo,
          vehicleAlias: vehicleList[i].vehicleAlias,
          modelSid: vehicleList[i].modelSid,
          configName: vehicleList[i].configName,
          configSid: vehicleList[i].configSid,
          inventoryLocationName: vehicleList[i].inventoryLocationName,
          witPinMoney: vehicleList[i].witPinMoney,
          invoiceTypeValue: vehicleList[i].invoiceTypeValue,
          freight: vehicleList[i].freight,
          freightUndertakerName: vehicleList[i].freightUndertakerName,
          remarks: vehicleList[i].remarks
        })
      }
      console.log('车辆表数据', this.list)
    },
    // 明细表删除一行数据
    dataDelete(row, index) {
      console.log('index', index, 'row', row)
      this.list.splice(index, 1)
    },

    showAdd() {
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      // this.temp.name = window.sessionStorage.getItem('name')
      this.temp.createBySid = window.sessionStorage.getItem('userSid')
      // req.detailsInfo(this.temp.sid).then(resp => {
      //   const data = resp.data
      //   this.temp.applicationCode = data.applicationCode
      //   this.temp.createTime = data.createTime
      // }).catch(e => {
      //   this.submitdisabled = false
      // })
      this.dialogStatus = 'add'
      this.viewTitle = '【新增】分公司间调账申请'
      this.getPathSid()
      this.getType()
      this.getListOrgAll()
    },

    showEdit(businessSid,instanceId,taskId) {
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      this.dialogStatus = 'edit'
      this.viewTitle = '【编辑】分公司间调账申请'
      fetchDetailsBySid(businessSid).then(resp => {
        if (resp.success) {
          const data = resp.data
          this.temp = data
          this.temp.instanceId = instanceId
          this.temp.taskId = taskId
          this.list = data.baseInternalPurchaseVehicles
          this.temp.createBySid = window.sessionStorage.getItem('userSid')
          this.temp.accSids = []
          console.log('编辑初始化', this.temp)
        }
      }).catch(e => {
        this.submitdisabled = false
      })
      this.getPathSid()
      this.getType()
      this.getListOrgAll()
    },
    handleCreate() {
      const _this = this
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          if (this.list.length > 0) {
            this.submitdisabled = true
            this.list.forEach(element => {
              this.temp.accSids.push(element.sid)
            })
            save(this.temp).then(resp => {
              this.submitdisabled = false
              if (resp.success) {
                if (resp.success) {
                  window.parent.postMessage({
                    cmd: 'returnHeight',
                    params: {
                      // 操作成功，告诉父级页面关闭弹框
                      code: 1
                    }
                  }, '*')
                }
              }
            }).catch(() => {
              this.submitdisabled = false
            })
          } else {
            this.$message({
              showClose: true,
              message: '请选择申请车辆',
              type: 'error'
            })
            return
          }
        } else {
          return false
        }
      })
    },
    handleSubmit() {
      const _this = this
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          if (this.list.length > 0) {
            this.submitdisabled = true
            this.$confirm('是否确定提交该业务', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.list.forEach(element => {
                this.temp.accSids.push(element.sid)
              })
              this.temp.detailsList = this.list
              submitAccAdjApply(this.temp).then(resp => {
                this.submitdisabled = false
                if (resp.success) {
                  if (resp.success) {
                    window.parent.postMessage({
                      cmd: 'returnHeight',
                      params: {
                        // 操作成功，告诉父级页面关闭弹框
                        code: 1
                      }
                    }, '*')
                  }
                }
              }).catch(() => {
                this.submitdisabled = false
              })
            })
          } else {
            this.$message({
              showClose: true,
              message: '请选择申请车辆',
              type: 'error'
            })
            return
          }
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style scoped>
.title {
  padding: 28px 0;
  text-align: center;
}
</style>
