<template>
	<div>
    <div v-show="viewState == 1">
		<!-- 标题按钮部分开始 -->
		<div class="tab-header webtop">
			<!-- 标题 -->
			<div>{{ viewTitle }}</div>
			<!-- start 添加修改按钮 -->
			<div>
				<el-button type="primary" size="small" :disabled="submitdisabled" @click="saveOrUpdate">保存</el-button>
				<el-button type="primary" size="small" :disabled="submitdisabled" @click="doSubmit">提交</el-button>
				<el-button type="info" size="small" @click="handleReturn()">返回</el-button>
			</div>
			<!-- end 添加修改按钮 -->
			<!-- end 详情按钮 -->
		</div>
		<!-- 标题按钮部分结束 -->
		<!-- Start 新增修改部分 -->
		<div class="listconadd">
			<el-form ref="form_obj" :model="formobj" :rules="rules" label-position="right" class="formadd">
				<div class="wlInfo" style="text-align: center;"><span style="font-size:28px;">外采申请表</span></div>
        <br><br>
				<el-row style="border-left: none;">
					<el-col :span="3" class="tleftb">
						<span><span class="icon">*</span>申请编号</span>
					</el-col>
					<el-col :span="5" class="trightb">
						<el-form-item prop="applicationCode">{{formobj.applicationCode}}</el-form-item>
					</el-col>
					<el-col :span="3" class="tleftb">
						<span><span class="icon">*</span>申请人</span>
					</el-col>
					<el-col :span="5" class="trightb">
						<el-form-item prop="createByName">{{formobj.createByName}}</el-form-item>
					</el-col>
					<el-col :span="3" class="tleftb">
						<span><span class="icon">*</span>申请日期</span>
					</el-col>
					<el-col :span="5" class="trightb">
						<el-form-item prop="applicationDate">{{formobj.applicationDate}}</el-form-item>
					</el-col>
				</el-row>
				<el-row style="border-left: none;">
					<el-col :span="3" class="tleftb">
						<span><span class="icon">*</span>外采类型</span>
					</el-col>
					<el-col :span="21" class="trightb" >
            <el-radio v-model="formobj.externalMiningTypeKey"  label="1">直接外采</el-radio>
            <el-radio v-model="formobj.externalMiningTypeKey"  label="2">政策外采</el-radio>
					</el-col>
				</el-row>
				<el-row style="border-left: none; ">
					<el-col :span="3" class="tleftb">
						<span><span class="icon">*</span>采购单位</span>
					</el-col>
					<el-col :span="21" class="trightb">
						<el-form-item prop="purchasingUnitName"><el-input size="small" v-model="formobj.purchasingUnitName" placeholder="采购单位" class="addinputw" clearable /></el-form-item>
					</el-col>
				</el-row>
				<el-row style="border-left: none;">
					<el-col :span="3" class="tleftb">
						<span><span class="icon">*</span>车型</span>
					</el-col>
					<el-col :span="19" class="trightb">
						<el-form-item prop="modelName">{{formobj.modelName}}</el-form-item>
					</el-col>
          <el-col :span="2" class="trightb">
            <!--<button  type="primary" size="small"  @click="saveOrUpdate">选择</button>-->
            <el-button type="primary" size="small" @click="selectModel">选择</el-button>
          </el-col>
				</el-row>
				<el-row style="border-left: none;">
					<el-col :span="3" class="tleftb">
						<span><span class="icon">*</span>常用配置名称</span>
					</el-col>
					<el-col :span="21" class="trightb">
						<el-form-item prop="configName">{{formobj.configName}}</el-form-item>
					</el-col>
				</el-row>
				<el-row style="border-left: none;">
					<el-col :span="3" class="tleftb">
						<span><span class="icon">*</span>采购价格</span>
					</el-col>
					<el-col :span="9" class="trightb">
						<el-form-item prop="purchasePrice"><el-input size="small" v-model="formobj.purchasePrice" placeholder="采购价格" class="addinputw" clearable /></el-form-item>
					</el-col>
					<el-col :span="3" class="tleftb">
						<span><span class="icon">*</span>销售指导价</span>
					</el-col>
					<el-col :span="9" class="trightb">
						<el-form-item v-show="formobj.externalMiningTypeKey==1" prop="guidedPrice"><el-input size="small" v-model="formobj.guidedPrice" placeholder="销售指导价" class="addinputw" clearable /></el-form-item>
            <el-form-item v-show="formobj.externalMiningTypeKey==2" prop="guidedPrice">{{formobj.guidedPrice}}</el-form-item>
					</el-col>
				</el-row>
				<el-row style="border-left: none;">
					<el-col :span="3" class="tleftb">
						<span><span class="icon">*</span>厂家合同价</span>
					</el-col>
					<el-col :span="9" class="trightb">
            <el-form-item v-show="formobj.externalMiningTypeKey==1" prop="manufactorSettlementPrice"><el-input size="small"  v-model="formobj.manufactorSettlementPrice" placeholder="厂家合同价" class="addinputw" clearable /></el-form-item>
            <el-form-item  v-show="formobj.externalMiningTypeKey==2" prop="manufactorSettlementPrice">{{formobj.manufactorSettlementPrice}}</el-form-item>
          </el-col>
					<el-col :span="3" class="tleftb">
						<span><span class="icon">*</span>台数</span>
					</el-col>
					<el-col :span="9" class="trightb">
            <el-form-item  v-show="formobj.externalMiningTypeKey==1" prop="num"><el-input size="small" v-model="formobj.num" placeholder="台数" class="addinputw" clearable /></el-form-item>
            <el-form-item v-show="formobj.externalMiningTypeKey==2" prop="num">{{formobj.num}}</el-form-item>
					</el-col>
				</el-row>
        <el-row style="border-left: none;">
          <el-col :span="3" class="tleftb">
            <span><span class="icon">*</span>订金</span>
          </el-col>
          <el-col :span="21" class="trightb">
            <el-form-item prop="deposit"><el-input size="small" style="height:10px;" v-model="formobj.deposit" placeholder="订金" class="addinputw" clearable /></el-form-item>
          </el-col>
        </el-row>
				<el-row style="border-left: none;">
					<el-col :span="3" class="tleftb">
						<span><span class="icon">*</span>费用名称</span>
					</el-col>
					<el-col :span="9" class="trightb">
						<el-form-item prop="expenseName"><el-input size="small" v-model="formobj.expenseName" placeholder="费用名称" class="addinputw" clearable /></el-form-item>
					</el-col>
					<el-col :span="3" class="tleftb">
						<span><span class="icon">*</span>费用金额合计</span>
					</el-col>
					<el-col :span="9" class="trightb">
						<el-form-item prop="totalExpenseAmount"><el-input size="small" v-model="formobj.totalExpenseAmount" placeholder="费用金额合计" class="addinputw" clearable /></el-form-item>
					</el-col>
				</el-row>
        <div class="listcon" v-show="formobj.externalMiningTypeKey==2">
          <div style="border:1px solid #c0c0c0;padding:5px 5px 5px 5px;">
            车辆列表
            <el-button type="primary" size="small" @click="selectVehicleDialog">选择车辆</el-button>
          </div>
          <el-table :data="formobj.baseOutsourcingApplicationVehicleDtos" border style="width: 100%">‘
            <el-table-column width="60px" label="序号" type="index" align="center"/>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button type="danger" size="small" @click="deleteVehicle(scope.row)">删除</el-button>
              </template>
            </el-table-column>
            <el-table-column prop="vinNo" label="车架号" align="center"/>
          </el-table>
        </div>
      </el-form>
    </div>
    </div><!-- End 添加修改部分 -->
    <!-- 车型配置分页列表 -->
    <el-dialog
      title="车辆列表"
      :visible.sync="vehicleDialogVisible"
      width="90%"
      :show-close="true"
      :before-close="handleClose">
      <vehicle ref="cheliang" @doback="resetState" :selectedSids="selectedSids"
               :modelSid="formobj.modelSid"
               :configSid="formobj.configSid"/>
      <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="quedingVehicle(this)">确 定</el-button>
          </span>
    </el-dialog>

    <!-- 选择待办人 -->
    <modellibrary @doback="resetState" v-show="viewState == 1.2" ref="chexingxuanze" @handleChexing="selectChexing"></modellibrary>


    <el-dialog title="填写审批意见"  :visible.sync="nodeDialogVisible" width="80%">
      <el-form label-position="right" class="formadd" >
        <el-row>
          <el-col :span="4" class="tleftb">当前环节</el-col>
          <el-col :span="20" class="trightb">
            <!--当前环节指向下一环节-->
            <el-form-item prop="purchasingUnitName"><span>{{firstNode.name}}->{{ nextNode.name }}</span></el-form-item>
          </el-col>
        </el-row>
        <div style="text-align:center;margin-top: 20px;">
          <el-button type="primary" size="mini"  @click="agree">确 定</el-button>
          <el-button type="info " size="mini"  @click="closeNodeDialog">取 消</el-button>
        </div>
      </el-form>
    </el-dialog>
    <!-- 选择用户 的弹出框-->
    <el-dialog title="选择用户"  :visible.sync="nodeUserDialogVisible" width="80%">
      <el-form label-position="right" class="formadd" >
        <div  v-for="item in users">
          <el-row >
            <el-col :span="24" class="tleftb" style="text-align: left">{{item.dept}}</el-col>
          </el-row>
          <el-row >
            <el-col :span="24" class="trightb" >
              <el-radio-group v-model="userSid">
                <el-radio v-for="item in item.users" :key="item.sid" :label="item.sid"
                          @change="checkedUser(item)">{{ item.name }}</el-radio>
              </el-radio-group>
            </el-col>
          </el-row>
        </div>

      </el-form>
    </el-dialog>
  </div>
</template>
<script>

import modellibrary from '@/views/baseoutsourcingapplication/relation/modellibrary'
import req from '@/api/baseoutsourcingapplication/baseoutsourcingapplication'
import vehicle from '@/views/baseoutsourcingapplication/baseoutsourcingapplicationvehicle.vue'

export default {
  name: 'BaseOutsourcingApplicationAdd',
  components: {
    modellibrary, vehicle
  },
  data() {
    return {
      //第一个环节
      firstNode:{},
      //下一个环节
      nextNode:{},
      //角色sid
      roleSid:'',
      //可选择的下一环节的用户集合
      users:[],
      //点击提交按钮显示弹框
      nodeDialogVisible:false,
      //选择用户弹框
      nodeUserDialogVisible:false,
      selectedSids: '',
      vehicleDialogVisible: false,
      dialogVisible: false,
      viewState: '1',
      submitdisabled: false,
      viewTitle: '',
      formobj: {
        //下一环节的用户sid
        nextUserSid:'',
        sid: '',
        userSid:'',
        staffSid: window.sessionStorage.getItem('staffSid'),
        applicationCode: '', // 申请编号
        createByName: window.sessionStorage.getItem('name'), // 申请人姓名
        applicationDate: '', // 申请日期
        externalMiningTypeKey: '1', // 外采类型key
        externalMiningTypeValue: '', // 外采类型value
        purchasingUnitName: '', // 采购单位名称
        modelSid: '', // 车型sid
        modelName: '', // 车型名称
        configName: '', // 常用配置名称
        configSid: '', // 常用配置sid
        purchasePrice: '', // 采购价格
        guidedPrice: '', // 销售指导价
        manufactorSettlementPrice: '', // 厂家合同价
        num: '0', // 台数
        deposit: '', // 订金
        expenseName: '', // 费用名称
        totalExpenseAmount: '', // 费用金额合计
        orgSid: window.sessionStorage.getItem('orgSid'), // 部门sid
        baseOutsourcingApplicationVehicleDtos: []
      },
      rules: {
        createByName: [{ required: true, message: '申请人姓名不能为空', trigger: 'blur' }], // 申请人姓名
        externalMiningTypeKey: [{ required: true, message: '外采类型key不能为空', trigger: 'blur' }], // 外采类型key
        externalMiningTypeValue: [{ required: true, message: '外采类型value不能为空', trigger: 'blur' }], // 外采类型value
        purchasingUnitName: [{ required: true, message: '采购单位名称不能为空', trigger: 'blur' }], // 采购单位名称
        modelSid: [{ required: true, message: '车型不能为空', trigger: 'blur' }], // 车型sid
        configSid: [{ required: true, message: '常用配置不能为空', trigger: 'blur' }], // 常用配置名称
        purchasePrice: [{ required: true, message: '采购价格不能为空', trigger: 'blur' }], // 采购价格
        guidedPrice: [{ required: true, message: '销售指导价不能为空', trigger: 'blur' }], // 销售指导价
        manufactorSettlementPrice: [{ required: true, message: '厂家合同价不能为空', trigger: 'blur' }], // 厂家合同价
        num: [{ required: true, message: '台数不能为空', trigger: 'blur' }], // 台数
        deposit: [{ required: true, message: '订金不能为空', trigger: 'blur' }], // 订金
        expenseName: [{ required: true, message: '费用名称不能为空', trigger: 'blur' }], // 费用名称
        totalExpenseAmount: [{ required: true, message: '费用金额合计不能为空', trigger: 'blur' }], // 费用金额合计
        orgSid: [{ required: true, message: '部门sid不能为空', trigger: 'blur' }] // 部门sid
      }
    }
  },
  created() {
  },
  methods: {
    closeNodeDialog(){
      this.nodeDialogVisible = false
    },
    quedingVehicle() {
      var obj = this.$refs['cheliang'].getSids()
      var length = obj.length

      if (length < 1) {
        alert('必须选择一条数据!')
        return
      }
      this.formobj.num = length
      this.formobj.baseOutsourcingApplicationVehicleDtos = obj
      this.vehicleDialogVisible = false
    },
    resetState() {
      this.viewState = 1
      this.handReset()
    },
    selectModel() {
      this.viewState = '1.2'
      this.$refs['chexingxuanze'].showChexing()
    },
    selectChexing(info) {
      this.viewState = '1'
      this.formobj.modelSid = info.modelSid // 车型sid
      this.formobj.modelName = info.modelName // 车型名称
      this.formobj.configName = info.configName // 常用配置名称
      this.formobj.configSid = info.configSid // 常用配置sid
      this.formobj.guidedPrice = info.guidedPrice// 销售指导价
      this.formobj.manufactorSettlementPrice = info.manufactorSettlementPrice// 厂家合同价
    },
    selectVehicleDialog() {
      var objs = this.formobj.baseOutsourcingApplicationVehicleDtos
      var s = ''
      for (var i = 0; i < objs.length; i++) {
        if (i == objs.length - 1) {
          s = s + objs[i].sid
        } else {
          s = s + objs[i].sid + ','
        }
      }
      this.selectedSids = s
      this.vehicleDialogVisible = true
      this.$refs.cheliang.dosearch()
    },
    handleReturn(isreload) {
      if (isreload === 'true') this.$emit('reloadlist')
      this.formobj.id = ''
      this.formobj.sid = '' // SID
      this.applicationCode = '' // 申请编号
      this.createByName = '' // 申请人姓名
      this.applicationDate = '' // 申请日期
      this.externalMiningTypeKey = '' // 外采类型key
      this.externalMiningTypeValue = '' // 外采类型value
      this.purchasingUnitName = '' // 采购单位名称
      this.modelSid = '' // 车型sid
      this.modelName = '' // 车型名称
      this.configName = '' // 常用配置名称
      this.purchasePrice = '' // 采购价格
      this.guidedPrice = '' // 销售指导价
      this.manufactorSettlementPrice = '' // 厂家合同价
      this.num = '' // 台数
      this.deposit = '' // 订金
      this.expenseName = '' // 费用名称
      this.totalExpenseAmount = '' // 费用金额合计  this.$store.getters.userInfo.orgSid,
      this.orgSid = ''

      this.$refs['form_obj'].resetFields()
      this.$emit('doback')
    },

    showAdd() {
      this.$nextTick(() => {
        this.$refs['form_obj'].clearValidate()
      })
      this.viewTitle = '【新增】外采申请表'
    },
    showEdit(sid) {
      this.$nextTick(() => {
        this.$refs['form_obj'].clearValidate()
      })
      this.viewTitle = '【修改】外采申请表'
      const _this = this
      _this.formobj.sid = sid // SID
      req
        .fetchBySid(sid)
        .then(resp => {
          if (resp.success) {
            const vdata = resp.data
            _this.formobj.applicationCode = vdata.applicationCode // 申请编号
            _this.formobj.createByName = vdata.createByName // 申请人姓名
            _this.formobj.applicationDate = vdata.applicationDate // 申请日期
            _this.formobj.externalMiningTypeKey = vdata.externalMiningTypeKey // 外采类型key
            _this.formobj.externalMiningTypeValue = vdata.externalMiningTypeValue // 外采类型value
            _this.formobj.purchasingUnitName = vdata.purchasingUnitName // 采购单位名称
            _this.formobj.modelSid = vdata.modelSid // 车型sid
            _this.formobj.modelName = vdata.modelName // 车型名称
            _this.formobj.configName = vdata.configName // 常用配置名称
            _this.formobj.purchasePrice = vdata.purchasePrice // 采购价格
            _this.formobj.guidedPrice = vdata.guidedPrice // 销售指导价
            _this.formobj.manufactorSettlementPrice = vdata.manufactorSettlementPrice // 厂家合同价
            _this.formobj.num = vdata.num // 台数
            _this.formobj.deposit = vdata.deposit // 订金
            _this.formobj.expenseName = vdata.expenseName // 费用名称
            _this.formobj.totalExpenseAmount = vdata.totalExpenseAmount // 费用金额合计
            _this.formobj.orgSid = vdata.orgSid // 部门sid
            _this.formobj.baseOutsourcingApplicationVehicleDtos = vdata.baseOutsourcingApplicationVehicleVos // 部门sid
          } else {
            // 根据resp.code进行异常情况处理
          }
        })
        .catch(e => {
          this.formobj = sid
        })
    },
    handleClose() {
      this.vehicleDialogVisible = false
      this.dialogVisible = false
    },
    indexMethod(index) {
      /*     var pagestart=(this.queryParams.current-1) * this.queryParams.size;
           var pageindex=index+1+pagestart;
           return pageindex;*/
    },
    //打开选择用户的弹框，并且根据角色查询用户列表
   /* selectUser() {
      this.nodeUserDialogVisible = true;
      req.getUsers( this.roleSid ).then(res => {
        this.users = res.data
      })
    },*/
    //选择下一环节的用户
   /* checkedUser(val) {

      this.userName = val.name
      this.formobj.nextUserSid =val.sid
      this.nodeUserDialogVisible = false
    },*/
    doSubmit(row) {
      // 提交的代码
      this.submitdisabled = true
      this.formobj.userSid = window.sessionStorage.getItem('userSid')
      this.formobj.orgSid = this.$store.getters.orgSid
      //查验下一环节要用到，流程定义的id

      this.agree();
      /*req.getNextNodesForSubmit(this.formobj).then(resp=>{
        if (resp.success) {
          //第一个环节
          this.firstNode=resp.data[0];
          //下一环节
          this.nextNode=resp.data[1];
          //环节上配置的角色
          var candidateGroups=this.nextNode.candidateGroups;
          this.roleSid=candidateGroups[0];
          req.getNextUserSids( this.formobj.orgSid,this.roleSid ).then(res => {
            /!*this.users = res.data*!/
            this.formobj.nextUserSid =res.data
          })
        //  this.nodeDialogVisible = true
        }
        this.submitdisabled = false
      });*/
    },
    //选择用户后点击确定/同意时向后台传递数据，启动流程，并从第一个环节流转到下一个环节
    agree() {
      req
        .doSubmit(this.formobj)
        .then(resp => {
          this.submitdisabled = false
          if (resp.success) {
            // 加提交后的逻辑
            this.$message({ showClose: true, type: 'success', message: resp.msg })
            this.handleReturn('true')
          } else {
            // 根据resp.code进行异常情况处理
          }
        })
        .catch(() => {
          this.submitdisabled = false
        })
    },
    saveOrUpdate() {
      const _this = this
      this.formobj.userSid = window.sessionStorage.getItem('userSid')
      this.formobj.orgSid = this.$store.getters.orgSid
      if (this.formobj.externalMiningTypeKey == '1') {
        this.formobj.externalMiningTypeValue = '直接外采'
      } else if (this.formobj.externalMiningTypeKey == '2') {
        this.formobj.externalMiningTypeValue = '政策外采'
      }
      this.$refs['form_obj'].validate(valid => {
        if (valid) {
          this.submitdisabled = true
          req
            .saveOrUpdate(this.formobj)
            .then(resp => {
              this.submitdisabled = false
              if (resp.success) {
                _this.$message({ showClose: true, type: 'success', message: resp.msg })
                _this.handleReturn('true')
              } else {
                // 根据resp.code进行异常情况处理
              }
            })
            .catch(() => {
              this.submitdisabled = false
            })
        } else {
          return false
        }
      })
    },
    deleteVehicle(row) {
      var arr = this.formobj.baseOutsourcingApplicationVehicleDtos

      const tip = '请确认是否删除车架号为' + row.vinNo + '记录?'
      this.$confirm(tip, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        for (var i = 0; i < arr.length; i++) {
          if (row.vinNo == arr[i].vinNo) {
            arr.splice(i, 1)
          }
        }
        this.formobj.num = this.formobj.num - 1
      }).catch(() => {
      })

    }
  }
}
</script>

<style scoped>
/*.tleftb{
  text-align: right;
  font-size: 14px;
  color: #606266;
  line-height: 20px !important;
  font-weight: 600;
}
.formadd .el-row .el-col {
  border-right: 1px solid #e0e3eb;
  border-bottom: 1px solid #e0e3eb;
  padding: 0px 15px 0px 15px !important;
  !* min-height: 50px; *!
  line-height: 1;
}*/
</style>
