<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <el-dialog
          title="选择异常出库原因"
          :visible.sync="reasonDialogVisible"
          width="30%"
          :before-close="closeReasonDialog"
        >
          <el-form ref="reasonForm" :model="reasonForm" label-width="80px">
            <el-form-item label="原因" prop="reason">
              <el-select v-model="reasonForm.reason" placeholder="请选择异常出库原因">
                <el-option
                  v-for="item in dict.reason"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="closeReasonDialog">取消</el-button>
            <el-button type="primary" @click="submitReason">确认</el-button>
          </div>
        </el-dialog>
        <el-form
          :inline="true"
          class="demo-form-inline"
          label-position="right"
          label-width="90px"
          label-suffix=":"
        >
          <el-form-item label="所属车间">
            <el-select
              v-model="query.workshop_code"
              clearable
              size="mini"
              placeholder="所属车间"
              class="filter-item"
            >
              <el-option
                v-for="item in workShopList"
                :label="item.workshop_name"
                :value="item.workshop_code"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="模糊搜索">
            <el-input
              v-model="query.blurry"
              clearable
              size="mini"
              placeholder="编码名称"
              @keyup.enter.native="crud.toQuery"
            />
          </el-form-item>
          <el-form-item label="区域类型">
            <el-select
              v-model="query.region_code"
              clearable
              filterable
              size="mini"
              placeholder="区域类型"
              class="filter-item"
              @clear="handleClear"
              @change="getPointStatusAndTypeList(query.region_code, 1)"
            >
              <el-option
                v-for="item in regionList"
                :label="item.region_name"
                :value="item.region_code"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="点位类型">
            <el-select
              v-model="query.point_type"
              clearable
              size="mini"
              placeholder="点位类型"
              class="filter-item"
              @change="hand"
            >
              <el-option
                v-for="item in pointTypesList"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="点位状态">
            <el-select
              v-model="query.point_status"
              clearable
              filterable
              size="mini"
              placeholder="点位状态"
              class="filter-item"
              @change="hand"
            >
              <el-option
                v-for="item in pointStatusList"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="母托盘编码">
            <el-input
              v-model="query.vehicle_code"
              clearable
              size="mini"
              placeholder="母托盘编码"
              @keyup.enter.native="crud.toQuery"
            />
          </el-form-item>
          <el-form-item label="子托盘编码">
            <el-input
              v-model="query.vehicle_code2"
              clearable
              size="mini"
              placeholder="子托盘编码"
              @keyup.enter.native="crud.toQuery"
            />
          </el-form-item>
          <el-form-item label="锁定类型">
            <el-switch
              v-model="query.lock_type"
              :active-value="true"
              :inactive-value="false"
              active-color="#409EFF"
              inactive-color="#C0CCDA"
              @change="hand"
            />
          </el-form-item>
          <el-form-item label="是否启用">
            <el-switch
              v-model="query.is_used"
              active-value="true"
              inactive-value="false"
              active-color="#409EFF"
              inactive-color="#C0CCDA"
              @change="hand"
            />
          </el-form-item>
          <rrOperation />
        </el-form>
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission">
        <el-button
          v-if="crud.query.is_used == 'false'"
          slot="right"
          class="filter-item"
          size="mini"
          type="primary"
          icon="el-icon-circle-check"
          :disabled="crud.selections.length === 0"
          @click="changeUsed(crud.selections, true)"
        >
          启用
        </el-button>
        <el-button
          v-if="crud.query.is_used == 'true'"
          slot="right"
          class="filter-item"
          size="mini"
          type="primary"
          icon="el-icon-circle-close"
          :disabled="crud.selections.length === 0"
          @click="changeUsed(crud.selections, false)"
        >
          禁用
        </el-button>
      </crudOperation>
      <el-dialog
        title="确认"
        :visible.sync="dialogVisible"
        width="30%"
      >
        <span>您确定要移库吗？</span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmMove">确定</el-button>
        </span>
      </el-dialog>
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="540px">
        <el-form ref="form" :model="form" :rules="rules" size="mini" label-width="110px" style="border: 1px solid #cfe0df;margin-top: 10px;padding-top: 10px;">
          <el-form-item v-if="false" label="点位标识" prop="point_id">
            <el-input v-model="form.point_id" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="所属车间">
            <el-select
              v-model="form.workshop_code"
              placeholder="请选择"
              style="width: 370px;"
            >
              <el-option
                v-for="item in workShopList"
                :label="item.workshop_name"
                :value="item.workshop_code"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="所属区域" prop="region_code">
            <el-select
              v-model="form.region_code"
              placeholder="请选择"
              style="width: 370px;"
              @change="getPointStatusAndTypeList(form.region_code, 2)"
            >
              <el-option
                v-for="item in regionList"
                :label="item.region_name"
                :value="item.region_code"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="点位编码" prop="point_code">
            <el-input v-model="form.point_code" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="点位名称" prop="point_name">
            <el-input v-model="form.point_name" style="width: 370px;" />
          </el-form-item>
          <el-form-item v-if="pointStatusDialogList.length > 0" label="点位状态" prop="point_status">
            <el-select
              v-model="form.point_status"
              size="mini"
              placeholder="点位状态"
              class="filter-item"
              style="width: 370px;"
              clearable
            >
              <el-option
                v-for="item in pointStatusDialogList"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item v-show="pointTypesDialogList.length > 0" label="点位类型" prop="device_point_type">
            <el-select
              v-model="form.point_type"
              size="mini"
              placeholder="设备点位类型"
              class="filter-item"
              style="width: 370px;"
            >
              <el-option
                v-for="item in pointTypesDialogList"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="父类编码" prop="vehicle_code">
            <el-input v-model="form.parent_point_code" clearable style="width: 370px;" @focus="getParentPoint" />
          </el-form-item>
          <el-form-item label="物料类型" prop="vehicle_type">
            <el-input v-model="form.vehicle_type" style="width: 370px;" />
          </el-form-item>
          <el-form-item v-if="form.point_status !== '1'" label="母托盘编码" prop="vehicle_code">
            <el-input v-model="form.vehicle_code" clearable style="width: 370px;" />
          </el-form-item>
          <el-form-item v-if="form.point_status !== '1'" label="子托盘编码" prop="vehicle_code2">
            <el-input v-model="form.vehicle_code2" clearable style="width: 370px;" />
          </el-form-item>
          <el-form-item label="载具数量" prop="vehicle_qty">
            <el-input-number v-model="form.vehicle_qty" style="width: 370px;" :controls="false" class="clear-number-input" :min="0" :precision="0" :max="99999" label="载具数量" size="mini" />
          </el-form-item>
          <el-form-item label="是否有工单">
            <el-radio v-for="item in dict.TrueOrFalse" :key="item.id" v-model="form.is_has_workder" :label="item.value">{{ item.label }}</el-radio>
          </el-form-item>
          <el-form-item label="是否自动">
            <el-radio v-for="item in dict.TrueOrFalse" :key="item.id" v-model="form.is_auto" :label="item.value">{{ item.label }}</el-radio>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="form.remark" style="width: 370px;" rows="2" type="textarea" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.cu === 2" type="primary" @click="mysubmit">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="mini" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="workshop_code" label="车间编码" :min-width="flexWidth('workshop_code',crud.data,'车间编码')" />
        <el-table-column prop="point_code" label="点位编码" :min-width="flexWidth('point_code',crud.data,'点位编码')" />
        <el-table-column prop="point_name" label="点位名称" :min-width="flexWidth('point_name',crud.data,'点位名称')" />
        <el-table-column prop="region_code" label="区域编码" :min-width="flexWidth('region_code',crud.data,'区域编码')" />
        <el-table-column prop="region_name" label="区域名称" :min-width="flexWidth('region_name',crud.data,'区域名称')" />
        <el-table-column prop="point_status_name" label="点位状态" :min-width="flexWidth('point_status_name',crud.data,'点位类型')" />
        <el-table-column prop="vehicle_code" label="母托盘编码" :min-width="flexWidth('vehicle_code',crud.data,'母托盘编码')" />
        <el-table-column prop="vehicle_code2" label="子托盘编码" :min-width="flexWidth('vehicle_code2',crud.data,'子托盘编码')" />
        <el-table-column prop="vehicle_qty" label="载具数量" :min-width="flexWidth('vehicle_qty',crud.data,'载具数量')" />
        <el-table-column label="是否锁定" :min-width="flexWidth('vehicle_qty',crud.data,'是否锁定')">
          <template slot-scope="scope">
            {{ scope.row.ing_task_code?'是':'否' }}
          </template>
        </el-table-column>
        <el-table-column prop="parent_point_code" label="父点位编码" :min-width="flexWidth('parent_point_code',crud.data,'父点位编码')" />
        <el-table-column prop="ing_task_code" label="在执行的任务标识" :min-width="flexWidth('ing_task_code',crud.data,'在执行的任务标识')" />
        <el-table-column prop="row_num" label="排" :min-width="flexWidth('row_num',crud.data,'排')" />
        <el-table-column prop="col_num" label="列" :min-width="flexWidth('col_num',crud.data,'列')" />
        <el-table-column prop="layer_num" label="层" :min-width="flexWidth('layer_num',crud.data,'层')" />
        <el-table-column prop="is_has_workder" label="是否有工单" :min-width="flexWidth('is_has_workder',crud.data,'是否有工单')">
          <template slot-scope="scope">
            {{ scope.row.is_has_workder?'是':'否' }}
          </template>
        </el-table-column>
        <el-table-column prop="is_auto" label="是否自动" :min-width="flexWidth('is_auto',crud.data,'是否自动')">
          <template slot-scope="scope">
            {{ scope.row.is_auto?'是':'否' }}
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" :min-width="flexWidth('remark',crud.data,'备注')" />
        <el-table-column prop="is_used" label="是否启用" :min-width="flexWidth('is_used',crud.data,'是否启用')">
          <template slot-scope="scope">
            {{ scope.row.is_used?'是':'否' }}
          </template>
        </el-table-column>
        <el-table-column prop="create_name" label="创建人" :min-width="flexWidth('create_name',crud.data,'创建人')" />
        <el-table-column prop="create_time" label="创建时间" :min-width="flexWidth('create_time',crud.data,'创建时间')" />
        <el-table-column prop="update_name" label="修改人" :min-width="flexWidth('update_name',crud.data,'修改人')" />
        <el-table-column prop="update_time" label="修改时间" :min-width="flexWidth('update_time',crud.data,'修改时间')" />
        <el-table-column v-permission="[]" label="操作" width="120px" align="center" fixed="right">
          <template slot-scope="scope">
            <udOperation
              style="display: inline"
              :data="scope.row"
              :permission="permission"
              :disabled-dle="true"
            />
            <el-button
              v-if="showQtyButton(scope.row.vehicle_qty,scope.row.region_code)"
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="openReasonDialog(scope.row)"
            >
              异常出库
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
    <ViewDialog ref="viewDialog" />
    <PointDialog :dialog-show.sync="pointDialog" :is-single="false" @tableChanged="tableChanged" />
  </div>
</template>

<script>
import crudSchBasePoint from './schBasePoint'
import crudSchBaseRegion from '../region/schBaseRegion'
import CRUD, { crud, form, header, presenter } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import crudMdBaseWorkShop from '@/views/wms/basedata/workshop/mdBaseWorkshop'
import ViewDialog from '@/views/wms/sch/point/ViewDialog.vue'
import PointDialog from '@/views/wms/sch/point/PointDialog.vue'

const defaultForm = {
  point_code: null,
  point_name: null,
  region_code: null,
  region_name: null,
  point_type: null,
  point_status: null,
  can_material_type: null,
  can_vehicle_type: null,
  vehicle_max_qty: null,
  vehicle_type: null,
  vehicle_code: null,
  vehicle_qty: 0,
  block_num: null,
  row_num: null,
  col_num: null,
  layer_num: null,
  in_order_seq: null,
  out_order_seq: null,
  in_empty_seq: null,
  out_empty_seq: null,
  parent_point_code: null,
  ext_point_code: null,
  ing_task_code: null,
  is_has_workder: 'true',
  workshop_code: null,
  is_auto: 'true',
  remark: null,
  is_used: 'true',
  can_vehicle_types: null
}
export default {
  name: 'SchBasePoint',
  dicts: ['vehicle_type', 'TrueOrFalse', 'reason'],
  components: { PointDialog, ViewDialog, pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({
      title: '点位管理',
      url: 'api/schBasePoint',
      idField: 'point_code',
      sort: 'point_code,desc',
      crudMethod: { ...crudSchBasePoint },
      optShow: {
        add: true,
        edit: true,
        del: true,
        download: false,
        reset: true
      },
      query: {
        is_used: 'true',
        lock_type: false
      }
    })
  },
  data() {
    return {
      permission: {},
      rules: {
        point_code: [
          { required: true, message: '点位编码不能为空', trigger: 'blur' }
        ],
        point_name: [
          { required: true, message: '点位名称不能为空', trigger: 'blur' }
        ],
        point_type: [
          { required: true, message: '点位类型不能为空', trigger: 'blur' }
        ],
        region_code: [
          { required: true, message: '区域类型不能为空', trigger: 'blur' }
        ]
      }, reasonDialogVisible: false,
      reasonForm: {
        reason: ''
      },
      workShopList: [],
      regionList: [],
      pointTypesList: [],
      pointStatusList: [],
      pointStatusDialogList: [],
      pointTypesDialogList: [],
      pointDialog: false,
      dialogVisible: false
    }
  },
  created() {
    this.getWorkShopList()
    this.getRegionList()
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    [CRUD.HOOK.beforeToCU]() {
      this.form.is_has_workder = this.form.is_has_workder.toString()
      this.form.is_auto = this.form.is_auto.toString()
    },
    [CRUD.HOOK.afterToCU]() {
      if (this.form.region_code) {
        this.getPointStatusAndTypeList(this.form.region_code, 2)
      }
    },
    hand(value) {
      this.crud.toQuery()
    },
    getWorkShopList() { // 获取车间列表
      crudMdBaseWorkShop.getWorkShopList().then(res => {
        this.workShopList = res
      })
    },
    getRegionList() {
      crudSchBaseRegion.getRegionList().then(res => {
        this.regionList = res
      })
    },
    getPointStatusAndTypeList(id, flag) {
      if (id) {
        this.getPointStatusList(id, flag)
        this.getPointTypeList(id, flag)
      }
      if (flag === 1) {
        this.crud.toQuery()
      }
    },
    getPointStatusList(id, flag) {
      crudSchBaseRegion.getPointStatusSelectById(id).then(res => {
        if (flag === 1) {
          this.pointStatusList = res
        } else {
          this.pointStatusDialogList = res
        }
      })
    },
    getPointTypeList(id, flag) {
      crudSchBaseRegion.getPointTypeSelectById(id).then(res => {
        if (flag === 1) {
          this.pointTypesList = res
        } else {
          this.pointTypesDialogList = res
        }
      })
    },
    changeUsed(data, flag) { // 更改启用状态
      const param = {}
      param.data = data
      param.used = flag
      crudSchBasePoint.changeUsed(param).then(res => {
        this.crud.notify('操作成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
        this.crud.toQuery()
      })
    },
    showQtyButton(vehicle_qty, region_code) {
      if (vehicle_qty === 1 && (region_code === 'YL' || region_code === 'YLHC')) {
        return true
      }
      return false
    },
    showButton(point_status) {
      if (point_status && point_status === '2') {
        return true
      }
      return false
    },
    toView(row) {
      if (row) {
        this.$refs.viewDialog.setParentData(row)
      }
    },
    tableChanged(row) {
      this.form.parent_point_code = row.map(point => point.point_code).join(',')
    },
    getParentPoint() {
      this.pointDialog = true
    },
    handleClear() {
      this.crud.query.region_code = null
      this.crud.query.point_type = null
      this.crud.query.point_status = null
      this.hand()
    },
    openReasonDialog(row) {
      // 打开选择原因的对话框
      this.reasonDialogVisible = true
      // 这里可以将row存储到data中，以便在提交时使用
      this.selectedRow = row
    },
    closeReasonDialog() {
      // 关闭选择原因的对话框
      this.reasonDialogVisible = false
      this.$refs['reasonForm'].resetFields()
    },
    submitReason() {
      // 提交选择的原因到后端接口
      const data = {
        reason: this.reasonForm.reason,
        device_code: this.selectedRow.point_code
      }
      // 调用后端接口提交数据
      // 这里假设使用axios库发送POST请求
      this.$axios
        .post('/api/schBasePoint/outbound', data)
        .then(response => {
          // 处理后端返回的数据
          console.log('提交成功', response)
          this.$message.success('提交成功')
          this.closeReasonDialog()
        })
        .catch(error => {
          // 处理错误情况
          console.error('提交失败,废包材位有货', error)
          this.$message.error('提交失败,废包材位有货')
        })
    },
    showConfirmationDialog() {
      this.dialogVisible = true
    },
    mysubmit() {
      // 弹出输入回温时间和回温模式的对话框
      this.$confirm('当前货位信息发生变更，请确认货位信息与实际一致', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log('提交')
        this.crud.submitCU('form')
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    confirmMove() {
      this.$axios.post('/api/schBaseTask/move', { })
        .then(response => {
          console.log(response.data)
        })
        .catch(error => {
          // Handle error response
          console.error(error)
        })
        .finally(() => {
          this.dialogVisible = false // Close the dialog
        })
    }
  }
}
</script>

<style scoped>

</style>
