<template>
  <!-- <strategy-view :strategyType="strategyType" :title="title" /> -->
  <div>
    <p-card style="width: 100%" title="策略">
      <p-grid-form ref="getForm" :span="8" :items="items" @submit="hanlderSubmit" />
      <p-table
      v-if="columns"
        dragle
        :has-row-count="true"
        :columns="columns"
        row-key="rqcStId"
        :scroll="{ x: 2000 }"
        :rowSelectFixed="true"
        :remoteUrl="remoteUrl"
        :remoteParams="remoteParams"
        :hasRowSelectCheck="true"
        :rowSelectType="1"
        @clickRow="mainClickRow"
        @selectChange="selectChange"
        :autoLoad="false"
        dataSource.sync="data"
      >
        <template v-slot:operation="text, record">
          <a @click="edit(record)">详情</a>
          <a-divider type="vertical" />
          <a @click="detelMain(record)">删除</a>
        </template>
      </p-table>
      <p-button type="primary" slot="extra" @click="mainBtn">添加</p-button>
      <p-modal
        title="策略"
        :visible="visible"
        :enlargeable="true"
        :draggable="true"
        width="80%"
        @ok="handleOk"
        @cancel="handleCancel"
        @enlargeChange="enlargeChange"
      >
        <p-grid-form ref="mainForm" :span="8" :items="mainItems" @submit="hanlderSubmit" />
      </p-modal>
    </p-card>
    <p-card style="width: 100%" title="策略规则">
      <p-table
        dragle
        :has-row-count="true"
        :columns="tableColumns"
        :scroll="{ x: 2000 }"
        row-key="ruleId"
        :rowSelectFixed="true"
        :hasRowSelectCheck="true"
        :rowSelectType="false"
        :dataSource.sync="tableData"
      >
        <template v-slot:operation="text, record">
          <p-button type="link" :disabled="record._row_count == 1" @click="moveUp(record)">上移</p-button>
          <p-button type="link" @click="moveDown(record)">下移</p-button>
          <p-button type="link" @click="detailEdit(record)">详情</p-button>
          <p-button type="link" @click="detailDel(record)">删除</p-button>
        </template>
      </p-table>
      <p-tooltip slot="extra" placement="topLeft" :title="tip">
        <p-button>规则说明</p-button>
      </p-tooltip>
      <p-button style="margin-left: 5px" type="primary" slot="extra" :disabled="btnDis" @click="detailBtn"
        >添加</p-button
      >
      <p-modal
        title="策略规则"
        :visible="visible1"
        :enlargeable="true"
        :draggable="true"
        width="80%"
        @ok="deatilOK"
        @cancel="handleCancel1"
        :destroyOnClose="true"
      >
        <p-grid-form ref="detailForm" :span="8" :items="detailItems" @submit="hanlderSubmit" />
      </p-modal>
    </p-card>
  </div>
</template>

<script>
import StrategyView from '../index.vue'
import { setFormItems, columns, tableColumns, mainItems, detailItems } from './js/config'

import {
  findAll,
  addMain,
  detailAdd,
  delMain,
  detailDel,
  editMain,
  editDetail,
  move,
} from './api/index'
import { upcloud_base_wh_inbound } from '@/config/serviceSettings'
import { getCargoOwner,forSelectText } from '../../../utils'
import { sorter } from '../../../utils/sort'

export default {
  data() {
    return {
      items: setFormItems(this),
      columns: null,
      tableColumns:tableColumns,
      data: [],
      remoteUrl: {
        url: upcloud_base_wh_inbound + '/wmsInRqcSt/findAll',
        method: 'post',
      },
      remoteParams: {},
      tableData: [],
      btnDis: true,
      visible: false,
      mainItems: mainItems(this),
      visible1: false,
      detailItems: detailItems(this),
      selectedRows: {},
      result: 0,
      detailResult: 0,
      categoryCode: '', //大类
      tip: 'x: 数量 c: 包装含量r: 结果x/c : 件数math.ceil() : 向上取整函数具体请参考基本的数学表达式和Aviator表达式',
    }
  },
  components: {
    StrategyView,
  },

  created() {
    this.getCargoOwnerFirst()
    this.initData()
  },
  async mounted() {
    let warehouse = this.$store.state.user.warehouse
    if (Object.keys(warehouse).length > 0) {
      this.$refs.getForm.form.setFieldsValue(warehouse)
    }
  },
  methods: {
    initData(){
      forSelectText([columns]).then((arr) => {
        this.columns = sorter(arr[0])
      })
    },
    hanlderSubmit(evnet, form) {
      evnet.preventDefault()
      var that = this
      form.getForm().validateFields(function (err, vals) {
        if (err) return
        that.remoteParams = vals
      })
      this.initData()
    },
    selectChange(selectedRowKeys, selectedRows) {
      this.selectedRows = selectedRows
      if (selectedRows.length > 0) {
        this.btnDis = false
        return
      } else {
        this.btnDis = true
        return
      }
    },
    //重置
    reset() {
      this.$refs.getForm.form.resetFields()
      this.data = []
      this.tableData = []
    },
    //主表点击行
    mainClickRow(event, activeID, rowRecord) {
      if (!activeID) {
        this.tableData = []
        return
      }
      var params = rowRecord
      findAll({ rqcStId: params.rqcStId }).then((res) => {
        if (!res.success) {
          this.$exception(res)
          return
        }
        this.tableData = res.data
      })
    },
    //主表
    handleOk(e) {
      this.$refs.mainForm.form.validateFields((error, values) => {
        if (!error) {
          values.mtlOwnerId = values.cargoOwnerId
          values.attribute1 = values.itemCategoryCode //商品大类编码
          values.attribute2 = values.itemId //商品编码
          // result 1 新增、2编辑
          if (this.result === 1) {
            if (values.stType == '1' && !values.itemCategoryCode) {
              this.$message.warning('策略类型为非通用时，商品大类必填，请检查！')
              return
            }
            this.$confirm({
              content: this.$lang('是否确定提交?'),
              onOk: () => {
                return this.handleAdd(values)
              },
            })
          } else {
            this.$confirm({
              content: this.$lang('是否确定提交?'),
              onOk: () => {
                return this.handleEdit(values)
              },
            })
          }
        }
      })
    },
    //新增主表
    handleAdd(params) {
      return addMain(params).then((res) => {
        if (!res.success) {
          this.$exception(res)
          return
        }
        this.visible = false
        this.$message.success('新增成功')
        this.$refs.mainForm.form.resetFields()
        this.getlist()
      })
    },

    //刷新
    getlist() {
      let form = this.$refs.getForm.form.getFieldsValue()
      this.remoteParams = form
    },
    // 编辑主表
    handleEdit(params) {
      return editMain(params).then((res) => {
        if (!res.success) {
          this.$exception(res)
          return
        }
        this.visible = false
        this.$message.success('修改成功')
        this.$refs.mainForm.form.resetFields()
        this.getlist()
      })
    },
    handleCancel(e) {
      this.visible = false
    },
    handleCancel1(e) {
      this.visible1 = false
    },
    enlargeChange(isEnlarge) {
      console.log(isEnlarge)
    },
    //跳转新增主表
    mainBtn() {
      this.visible = true
      this.result = 1
      var warehouse = this.$refs.getForm.form.getFieldsValue()
      var that = this
      this.$nextTick(() => {
        that.$refs.mainForm.form.resetFields()
        that.$refs.mainForm.form.unhiddenItem(['warehouseName', 'cargoOwnerName'])
        that.$refs.mainForm.form.hiddenItem(['itemCategoryCode', 'itemName'])
        that.$refs.mainForm.form.setFieldsValue({
          warehouseId: warehouse.warehouseId,
          warehouseCode: warehouse.warehouseCode,
          warehouseName: warehouse.warehouseName,
          cargoOwnerId: warehouse.cargoOwnerId,
          cargoOwnerCode: warehouse.cargoOwnerCode,
          cargoOwnerName: warehouse.cargoOwnerName,
        })
      })
    },

    //跳转新增明细
    detailBtn() {
      this.visible1 = true
      var that = this
      this.detailResult = 1
      this.$nextTick(() => {
        that.$refs.detailForm.form.setFieldsValue({
          rqcStId: that.selectedRows[0].rqcStId,
        })
      })
    },
    // 编辑主表详情
    edit(record) {
      console.log(record, '编辑主表详情')
      this.visible = true
      this.result = 2
      var that = this
      var formData = this.$refs.getForm.form.getFieldsValue()
      this.$nextTick(() => {
        record.warehouseId = formData.warehouseId
        record.warehouseCode = formData.warehouseCode
        record.warehouseName = formData.warehouseName
        record.cargoOwnerId = formData.cargoOwnerId
        record.cargoOwnerCode = formData.cargoOwnerCode
        record.cargoOwnerName = formData.cargoOwnerName
        that.$refs.mainForm.form.setFieldsValue(record)
        //非通用需要显示大类和商品
        if (record.stType != '1') {
          that.$refs.mainForm.form.hiddenItem(['itemCategoryCode', 'itemName'])
        } else {
          that.$refs.mainForm.form.unhiddenItem(['itemCategoryCode', 'itemName'])
        }
      })
    },
    // 删除主表详情
    detelMain(record) {
      this.$confirm({
        content: this.$lang('是否确定删除?'),
        onOk: () => {
          return this.delMain(record)
        },
      })
    },
    delMain(record) {
      let rqcStId = [record.rqcStId]
      return delMain(rqcStId).then((res) => {
        if (!res.success) {
          this.$exception(res)
          return
        }
        this.$message.success('删除成功')
        this.getlist()
      })
    },

    //规则新增
    deatilOK() {
      this.$refs.detailForm.form.validateFields((error, values) => {
        console.log(error, values, '111111111111')
        if (!error) {
          this.$confirm({
            content: this.$lang('是否确定提交?'),
            onOk: () => {
              // detailResult 1 新增、2编辑
              if (this.detailResult === 1) {
                return this.detailSave(values)
              } else {
                return this.detailEditSave(values)
              }
            },
          })
        }
      })
    },
    //明细新增
    detailSave(params) {
      return detailAdd(params).then((res) => {
        if (!res.success) {
          this.$exception(res)
          return
        }
        this.visible1 = false
        this.$message.success('新增成功')
        this.$refs.detailForm.form.resetFields()
        this.getRult()
      })
    },
    //明细编辑新增
    detailEditSave(params) {
      return editDetail(params).then((res) => {
        if (!res.success) {
          this.$exception(res)
          return
        }
        this.visible1 = false
        this.$message.success('新增成功')
        this.$refs.detailForm.form.resetFields()
        this.getRult()
      })
    },
    //明细编辑
    detailEdit(record) {
      this.visible1 = true
      this.detailResult = 2
      var that = this
      this.$nextTick(() => {
        that.$refs.detailForm.form.resetFields()
        that.$refs.detailForm.form.setFieldsValue(record)
      })
    },
    // 明细删除
    detailDel(record) {
      this.$confirm({
        content: this.$lang('是否确定删除?'),
        onOk: () => {
          return this.del(record)
        },
      })
    },
    del(record) {
      let ruleId = [record.ruleId]
      detailDel(ruleId).then((res) => {
        if (!res.success) {
          this.$exception(res)
          return
        }
        this.$message.success('删除成功')
        this.getRult()
      })
    },
    //上移
    moveUp(record) {
      var params = {}
      params.pkId = record.ruleId
      params.moveType = 'up'
      this.move(params)
    },
    // 下移
    moveDown(record) {
      var params = {}
      params.pkId = record.ruleId
      params.moveType = 'down'
      this.move(params)
    },

    //上下移
    move(params) {
      move(params).then((res) => {
        if (!res.success) {
          this.$exception(res)
          return
        }
        this.$message.success('移动成功')
        this.getRult()
      })
    },
    getRult() {
      var params = this.selectedRows[0]
      findAll({ rqcStId: params.rqcStId }).then((res) => {
        if (!res.success) {
          this.$exception(res)
          return
        }
        this.tableData = res.data
      })
    },

    //获取货主信息
    getCargoOwnerFirst() {
      getCargoOwner().then((res) => {
        if (!res.success) {
          this.$exception(res)
          return
        }
        this.$nextTick(() => {
          if (res.data.list.length > 1) {
            this.$refs.getForm.form.setFieldsValue({
              cargoOwnerId: res.data.list[0].companyId,
              cargoOwnerCode: res.data.list[0].companyCode,
              cargoOwnerName: res.data.list[0].companyName,
            })
          }
        })
      })
    },
  },
}
</script>

<style></style>
