<template>
  <div>
    <xy-dialog ref="dialog" :width='70' :is-show.sync="isShow" type="form" :title="titleName" :form="form"
      :rules="rules" @submit="submit">
      <template v-slot:chukushijian>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>出库时间：
          </div>
          <div class="xy-table-item-content">
            <el-date-picker style="width: 300px;" v-model="form.chukushijian" type="date" placeholder="选择日期"
              value-format="yyyy-MM-dd">
            </el-date-picker>
          </div>
        </div>
      </template>
      <!-- <template v-slot:chukuleixing>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>出库类型：
          </div>
          <div class="xy-table-item-content">
            <el-select v-model="form.chukuleixing" style="width: 300px;" placeholder="请选择">
              <el-option
                v-for="item in lexingoptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </div>
        </div>
      </template> -->
      <template v-slot:jieyongcangku>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;"></span>借用仓库：
          </div>
          <div class="xy-table-item-content">
            <el-select v-model="form.jieyongcangku" filterable style="width: 300px;" placeholder="请选择借用仓库">
              <el-option v-for="item in cangkuList" :key="item.cangkumingcheng" :label="item.cangkumingcheng"
                :value="item.cangkumingcheng">
              </el-option>
            </el-select>
          </div>
        </div>
      </template>
      <template v-slot:jieyongbumen>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;"></span>借用部门：
          </div>
          <div class="xy-table-item-content">
            <el-input v-model="form.jieyongbumen" placeholder="请填写借用部门" clearable style="width: 300px;"></el-input>
          </div>
        </div>
      </template>
      <!--      <template v-slot:jieyongren>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>借用人：
          </div>
          <div class="xy-table-item-content">
            <el-input v-model="form.jieyongren" placeholder="请填写借用人" clearable style="width: 300px;"></el-input>
          </div>
        </div>
      </template> -->

      <template v-slot:jilurenyuan>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>经办人：
          </div>
          <div class="xy-table-item-content">
            <el-input v-model="form.jilurenyuan" placeholder="请输入经办人" clearable style="width: 300px;"></el-input>
          </div>
        </div>
      </template>
      <template v-slot:baofeiyuanyin v-if="chukuType=='处置'">
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;"></span>报废原因：
          </div>
          <div class="xy-table-item-content">
            <el-input type="textarea" v-model="form.baofeiyuanyin" placeholder="请输入报废原因" clearable
              style="width: 300px;"></el-input>
          </div>
        </div>
      </template>
      <template v-slot:beizhu>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;"></span>备注：
          </div>
          <div class="xy-table-item-content">
            <el-input type="textarea" v-model="form.beizhu" placeholder="请输入备注" clearable
              style="width: 300px;"></el-input>
          </div>
        </div>
      </template>
      <template v-slot:chukumingxi>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;"></span>出库明细 ：
          </div>
          <div class="xy-table-item-content">
            <Button type="primary" icon="md-add" style="margin-bottom: 10px" @click="isShowMingxi=true">新增出库明细</Button>

            <xy-table style="width: 50%" :height="260" :is-page="false" :list="mingxiList" :table-item="mingxiTable">
              <template v-slot:btns>
                <el-table-column label="操作" width="90" header-align="center" align="center">
                  <template v-slot:default="scope">
                    <Poptip transfer confirm title="确认要删除吗？" @on-ok="delMingxiList(scope.$index,scope.row)">
                      <Button size="small" type="primary" ghost>删除</Button>
                    </Poptip>
                  </template>
                </el-table-column>
              </template>
            </xy-table>
          </div>
        </div>
      </template>
    </xy-dialog>
    <!-- 新增明细 -->
    <Modal v-model="isShowMingxi" width='600' title="新增明细" :loading='showLoading' @on-cancel='mingxiCancel'
      @on-ok="mingxiConfirm">
      <div class="mingxiwrap">
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>物资编码：
          </div>
          <div class="xy-table-item-content">
            <el-input type="text" @focus="showWuzi" v-model="mingxiObj.wuzibianma" placeholder="请选择物资编码"
              style="width: 300px;"></el-input>
          </div>
        </div>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;"></span>资产名称：
          </div>
          <div class="xy-table-item-content">
            <el-input type="text" v-model="mingxiObj.zichanmingcheng" placeholder="请选择资产名称" disabled
              style="width: 300px;"></el-input>
          </div>
        </div>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;"></span>规格型号：
          </div>
          <div class="xy-table-item-content">
            <el-input type="text" v-model="mingxiObj.guigexinghao" placeholder="请选择规格型号" disabled
              style="width: 300px;"></el-input>
          </div>
        </div>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;"></span>物资类型：
          </div>
          <div class="xy-table-item-content">
            <el-input type="text" v-model="mingxiObj.wuzileixing" placeholder="请选择物资类型" disabled
              style="width: 300px;"></el-input>
          </div>
        </div>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;"></span>入库批次：
          </div>
          <div class="xy-table-item-content">
            <el-input type="text" v-model="mingxiObj.rukupici" placeholder="请选择入库批次" disabled
              style="width: 300px;"></el-input>
          </div>
        </div>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;"></span>在库数量：
          </div>
          <div class="xy-table-item-content">
            <el-input type="text" v-model="mingxiObj.zaikushuliang" placeholder="请选择在库数量" disabled
              style="width: 300px;"></el-input>
          </div>
        </div>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;"></span>生产日期：
          </div>
          <div class="xy-table-item-content">
            <el-input type="text" v-model="mingxiObj.shengchanriqi" placeholder="请选择生产日期" disabled
              style="width: 300px;"></el-input>
          </div>
        </div>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>出库数量：
          </div>
          <div class="xy-table-item-content">
            <el-input type="text" @blur='jieyong' v-model="mingxiObj.jieyongshuliang" placeholder="请填写出库数量"
              style="width: 300px;"></el-input>
          </div>
        </div>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>是否回库：
          </div>
          <div class="xy-table-item-content">
            <el-select v-model="mingxiObj.shifouhuiku" style="width: 300px;" placeholder="请选择">
              <el-option v-for="item in huikuoptions" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </div>
        </div>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;"></span>回库时间：
          </div>
          <div class="xy-table-item-content">
            <el-date-picker style="width: 300px;" v-model="mingxiObj.huikushijian" type="date" placeholder="选择日期"
              value-format="yyyy-MM-dd">
            </el-date-picker>
          </div>
        </div>

      </div>

    </Modal>
    <!-- 选择库存 -->
    <Modal v-model="isShowWuzi" title="库存选择">
      <div class="searchCompanys">
        <el-input style="margin-right:10px" clearable type="text" @keyup.enter.native="getWuzi" v-model="wuzibianmakeyword" placeholder="请输入物资编码查找库存"></el-input>
        <el-input style="margin-right:10px" clearable type="text" @keyup.enter.native="getWuzi" v-model="keyword" placeholder="请输入物资名称查找库存"></el-input>


        <el-button type="primary" @click="getWuzi">查询</el-button>
      </div>
      <Table highlight-row ref="currentRowTable" :columns="wuziColumns" :data="wuziList"
        @on-current-change="wuziSelect" />
      <Page :current="wuziPageIndex" :total="wuziTotal" simple
        style="padding-top: 14px;display: flex;justify-content: center;" @on-change="wuziPageChange" />
    </Modal>



  </div>
</template>

<script>
  import {
    save,
    index,
    show,
    destroy
  } from "@/api/system/baseForm.js"
  import {
    desChuku
  } from "@/api/system/log.js"

  import {
    Message
  } from 'element-ui'
  export default {

    data() {
      return {
        isShow: false,
        type: 'add',
        id: '',
        authName: "",
        titleName: '',
        keyword: '',
        wuzibianmakeyword:'',
        chukuType: '',
        tableName: 'outbounds',
        cangkuList: [],
        lexingoptions: [{
          label: '领用',
          value: '领用'
        }, {
          label: '处置',
          value: '应急'
        }],
        huikuoptions: [{
          label: '是',
          value: '是'
        }, {
          label: '否',
          value: '否'
        }],
        form: {
          chukushijian: "",
          chukuleixing: '',
          jieyongcangku: "",
          jieyongbumen: '',
          // jieyongren:'',
          jilurenyuan: '',
          baofeiyuanyin: '',
          beizhu: '',
          chukumingxi: ''
        },
        rules: {
          chukushijian: [{
            required: true,
            message: '请选择出库时间'
          }],
          // chukuleixing: [{
          //   required: true,
          //   message: '请选择出库类型'
          // }],
          // jieyongren: [{
          //   required: true,
          //   message: '请填写借用人'
          // }],
          jilurenyuan: [{
            required: true,
            message: '请输入经办人'
          }],
        },
        isShowMingxi: false,
        mingxiObj: {
          wuzibianma: '',
          jieyongshuliang: '',
          shifouhuiku: '',
          huikushijian: ''
        },
        mingxiObjBefore: {},
        mingxiList: [],
        showLoading: true,
        mingxiIndex: '',
        mingxiTable: [{
            label: "物资编码",
            prop: "wuzibianma",
            width: 180
          },
          {
            label: "资产名称",
            prop: "zichanmingcheng",
            width: 180
          },
          {
            label: "规格型号",
            prop: "guigexinghao",
            width: 180
          }, {
            label: "物资类型",
            prop: "wuzileixing",
            width: 180
          }, {
            label: "计量单位",
            prop: "jiliangdanwei",
            width: 180
          }, {
            label: "入库批次",
            prop: "rukupici",
            width: 180
          }, , {
            label: "在库数量",
            prop: "zaikushuliang",
            width: 180
          },{

            label: "生产日期",
            prop: "shengchanriqi",
            width: 180
          } ,{
            label: "借用数量",
            prop: "jieyongshuliang",
            width: 180
          }, {
            label: "是否回库",
            prop: "shifouhuiku",
            width: 180
          }, , {
            label: "回库时间",
            prop: "huikushijian",
            width: 180
          }
        ],
        // 物资
        isShowWuzi: false,
        wuziList: [],
        wuziPageIndex: 1,
        wuziTotal: 0,
        wuziColumns: [{
            width: 60,
            _isChecked: false,
            key: "isSelect",
            resizable: true,
            render: (h, params) => {
              return h('div', [
                h('Radio', {
                  props: {
                    value: params.row.isSelect
                  },
                  on: {
                    'on-change': (e) => {
                      this.showList.forEach((items) => {
                        this.$set(items, 'isSelect', false)
                      });
                      this.showList[params.index].isSelect = e;
                    }
                  }
                })
              ])
            }
          },
          {
            title: '名称',
            key: 'names',
          },
          {
            title: '在库数量',
            key: 'zaikushuliang',
          },
          {
            title: '物资类型',
            key: 'wuzileixing',
          },
          {
            title: '入库批次',
            key: 'rukupici',
          },
          {
            title: '生产日期',
            key: 'shengchanriqi',
          },
        ],
        wuziList: []
      }
    },
    created() {
      this.getCangku()
      this.getWuzi()

    },
    methods: {
      jieyong() {
        if (parseInt(this.mingxiObj.jieyongshuliang) > parseInt(this.mingxiObj.zaikushuliang)|| parseInt(this.mingxiObj.zaikushuliang)===0) {
          Message({
            type: 'warning',
            message: '库存不足'
          })
          return false
        }
        if(parseInt(this.mingxiObj.jieyongshuliang)<1){
          Message({
            type: 'warning',
            message: '请填写正确的借用数量'
          })
          return false
        }
      },
      // 明细
      mingxiConfirm() {
        setTimeout(() => {
          this.showLoading = false
          this.$nextTick(() => {
            this.showLoading = true
          })
        }, 500)

        if (JSON.stringify(this.mingxiObj)=="{}"||this.mingxiObj.wuzibianma == '' || this.mingxiObj.jieyongshuliang == '' || this.mingxiObj.shifouhuiku ==
          '') {
          Message({
            type: 'warning',
            message: '请填写完整数据'
          })
          this.showLoading = false
          return
        }
        if (parseInt(this.mingxiObj.jieyongshuliang) > parseInt(this.mingxiObj.zaikushuliang) || parseInt(this.mingxiObj.zaikushuliang)===0) {
          Message({
            type: 'warning',
            message: '库存不足'
          })
          return
        }
        if (parseInt(this.mingxiObj.jieyongshuliang) < 1) {
          Message({
            type: 'warning',
            message: '请填写正确的借用数量'
          })
          return
        }
        if (this.mingxiIndex != '') {
          this.mingxiList[this.mingxiIndex - 1] = this.mingxiObj
        } else {
          this.mingxiList.push(this.mingxiObj)
        }
        this.wuziList.forEach((items) => {
          this.$set(items, 'isSelect', false)
        });

        this.mingxiObj = {
          wuzibianma: '',
          jieyongshuliang: '',
          shifouhuiku: '',
          huikushijian: ''
        }
        this.mingxiObjBefore = {}
        this.mingxiIndex = ''
        this.isShowMingxi = false
      },
      mingxiCancel() {
        this.wuziList.forEach((items) => {
          this.$set(items, 'isSelect', false)
        });
        this.mingxiObj = {
          wuzibianma: '',
          jieyongshuliang: '',
          shifouhuiku: '',
          huikushijian: ''
        }
        this.mingxiObjBefore = {}
        this.mingxiIndex = ''
        this.isShowMingxi = false
      },
      editMingxi(index) {
        const before = this.mingxiList[index]
        for (var m in this.mingxiList[index]) {
          this.mingxiObjBefore[m] = this.mingxiList[index][m]
        }
        this.mingxiObj = this.mingxiList[index]
        this.mingxiIndex = index + 1 // 为0时！=‘’为false
        this.isShowMingxi = true
      },
      // 删除明细记录
      delMingxiList(index,row){
        if(row.id){
          destroy({
            id:row.id,
            table_name:'outbounds_items'
          }).then(res=>{
            Message({
              type: 'success',
              message: '删除成功'
            })
            this.mingxiList.splice(index, 1)
          })
        }else{
          Message({
            type: 'success',
            message: '删除成功'
          })
          this.mingxiList.splice(index, 1)
        }
      },
      showWuzi() {
        this.isShowWuzi = true
      },
      async getWuzi() {
        let res = await index({
          page_size: 10,
          page: this.wuziPageIndex,
          table_name: 'inventorys',
          filter: [{
            "key": "zichanmingcheng",
            "op": "like",
            "value": this.keyword
          },{
            "key": "wuzibianma",
            "op": "like",
            "value": this.wuzibianmakeyword
          }]
        })
        for (var m of res.data) {
          m.names = m.wuzibianma + "--" + m.zichanmingcheng
          m.isSelect = false
        }
        this.wuziList = res.data
        this.wuziTotal = res.total
      },
      wuziSelect(e) {
        this.wuziList.forEach((items) => {
          this.$set(items, 'isSelect', false)
          if (items.id == e.id) {
            this.$set(items, 'isSelect', true)
            this.mingxiObj.wuzibianma = e.wuzibianma
            this.mingxiObj.zichanmingcheng = e.zichanmingcheng
            this.mingxiObj.wuzileixing = e.wuzileixing
            this.mingxiObj.rukupici = e.rukupici
            this.mingxiObj.zaikushuliang = e.zaikushuliang
            this.mingxiObj.jiliangdanwei = e.jiliangdanwei
            this.mingxiObj.inventorys_id = e.id
            this.mingxiObj.guigexinghao = e.guigexinghao
            this.mingxiObj.shengchanriqi = e.shengchanriqi
          }
        });
        this.mingxiList.map(item=>{
          if(item.inventorys_id===this.mingxiObj.inventorys_id){
            Message({
              type: 'warning',
              message: `${item.wuzibianma}${item.zichanmingcheng}已选择`
            })
            this.mingxiObj = {}
            return
          }
        })

      },
      wuziPageChange(e) {
        this.wuziPageIndex = e
        this.getWuzi()
      },
      async getCangku() {
        let res = await index({
          page_size: 999,
          page: 1,
          table_name: 'materialstorages',
        })
        this.cangkuList = res.data
      },
      async getDetail() {
        const res = await show({
          id: this.id,
          table_name: this.tableName
        })
        this.form = {
          chukushijian: res?.chukushijian,
          zhuangtai: res?.zhuangtai,
          jieyongcangku: res?.jieyongcangku,
          jieyongbumen: res?.jieyongbumen,
          // jieyongren:res?.jieyongren,
          jilurenyuan: res?.jilurenyuan,
          baofeiyuanyin: res?.baofeiyuanyin,
          beizhu: res?.beizhu,
          chukumingxi: ''
        }
        this.mingxiList = res.id_outbounds_items_outbounds_id_relation
      },
      countNum(arr,value){

      },
      isHasEqual(arr,key,key1) {
          if(arr.length===0){
            return
          }
          for(let i = 0; i < arr.length; i++) {
                if(arr.filter(item => item[key] == arr[i][key]).length > 1&&arr.filter(item => item[key1] == arr[i][key1]).length > 1) {

                      return true;
                  }

          }
          return false;
      },
      submit() {
        console.log("this.mingxiList",this.mingxiList)

        // return
        this.form.id_outbounds_items_outbounds_id_relation = this.mingxiList
        const has = this.isHasEqual(this.form.id_outbounds_items_outbounds_id_relation,"wuzibianma","rukupici")
        if(has){
          Message({
            type: 'warning',
            message: '同一物资同一批次请不要重复录入'
          })
          return
        }


        // return
        if (this.type === 'add') {
          this.form.zhuangtai = '待处理'
          save({
            table_name: this.tableName,
            ...this.form
          }).then(res => {
            Message({
              type: 'success',
              message: '新增成功'
            })
            this.isShow = false
            this.$emit('refresh')
          })
          return
        }
        if (this.type === 'editor' || this.type === 'outbounds') {
          if (this.type === 'outbounds') {
            this.form.zhuangtai = '已出库'
          }
          save({
            id: this.id,
            table_name: this.tableName,
            ...this.form
          }).then(res => {
            Message({
              type: 'success',
              message: '编辑成功'
            })
            if(this.form.zhuangtai = '已出库'){
              desChuku({
                outbound_id:this.id
              }).then(res=>{

              })
            }
            this.isShow = false
            this.$emit('refresh')
          })
        }
      },

    },
    watch: {
      isShow(newVal) {
        if (newVal) {
          this.titleName = this.type === 'add' ? `新增${this.chukuType}出库` : (this.type === 'editor' ?
            `编辑${this.chukuType}出库` : '出库')
          this.form.chukuleixing = this.chukuType
          if (this.type === 'editor' || this.type === 'outbounds') {
            this.getDetail()
          } else {
            this.form.jilurenyuan = this.authName
          }
        } else {
          this.id = ''
          this.type = ''
          this.mingxiList = []
          this.authName = ''
          this.$refs['dialog'].reset()
        }
      }
    }

  }
</script>

<style scoped lang="scss">
  .mingxiwrap {
    display: flex;
    flex-wrap: wrap;
  }

  .mingxiwrap .xy-table-item {
    margin-bottom: 10px
  }

  .searchCompanys {
    display: flex;
    justify-content: space-between;
    margin-bottom: 15px;
  }

  ::v-deep .searchCompanys .el-input {
    width: 82%
  }

  .xy-table-item-label {
    width: 160px;
  }

  .img__delete {
    transform: scale(0.8, 0.8);

    position: absolute;
    top: 4px;
    right: 4px;
  }

  ::v-deep .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  ::v-deep .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  ::v-deep .el-upload--picture-card {
    font-size: 28px;
    color: #8c939d;
    width: 80px !important;
    height: 80px !important;
    line-height: 80px !important;
    text-align: center;
  }

  ::v-deep .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 80px !important;
    height: 80px !important;
    line-height: 80px !important;
    text-align: center;
  }

  ::v-deep .avatar {
    width: 80px !important;
    display: block;
    border-radius: 6px;
  }

  ::v-deep .xy-table-item-label {
    width: 160px !important;
  }

  ::v-deep .el-date-editor .el-range-separator {
    width: auto !important;
  }

  ::v-deep .el-input-number .el-input__inner {
    text-align: left !important;
  }
</style>
