<template>
  <div>
    <!-- 策略表 -->
    <div>
      <!-- 策略 -->
      <p-card title="策略" :headStyle="{ border: 'none' }" :bordered="false" style="width: 100%">
        <div slot="extra"><p-button type="primary" @click="AddStrategy()">添加</p-button></div>
        <p-table
          bordered
          :remote-url="tablecolumns.MainTable.remoteUrl"
          :ref="tablecolumns.MainTable.ref"
          :row-key="tablecolumns.MainTable.rowkey"
          :columns="tablecolumns.MainTable.columns"
          :data-source.sync="data"
          :remoteParams="MainTableremoteParams"
          :rowSelectType="false"
          :done="loadExtendData"
          @clickRow="clickRow"
        >
          <span slot="enable" slot-scope="text, record">
            {{ text ? '启用' : '禁用' }}
          </span>
          <span slot="operation" slot-scope="text, record">
            <a @click.stop="AddStrategy(text)">编辑</a>
            <a-divider type="vertical" />
            <a v-if="!text.enable" @click="StrategyEnable(text)">启用</a>
            <a v-else @click="StrategyEnable(text)">禁用</a>
            <a-divider type="vertical" />
            <a @click.stop="DelMainTable(text)">删除</a>
          </span>
        </p-table>
      </p-card>
      <!--规则表  -->

      <a-divider />
      <p-card title="规则" :headStyle="{ border: 'none' }" :bordered="false" style="width: 100%">
        <div slot="extra">
          <p-button v-if="Object.keys(strategy).length > 0" type="primary" @click="addRuleTable">添加</p-button>
        </div>
        <p-table
          bordered
          :ref="tablecolumns.RuleTable.ref"
          :row-key="tablecolumns.RuleTable.rowkey"
          :columns="tablecolumns.RuleTable.columns"
          :data-source.sync="RuleTabledata"
          :remoteUrl="tablecolumns.RuleTable.remoteUrl"
          :remoteParams="RuleTableremoteParams"
          :autoLoad="false"
          :rowSelectType="false"
        >
          <span slot="disabled" slot-scope="text, record">
            {{ text ? '启用' : '禁用' }}
          </span>
          <span slot="operation" slot-scope="text, record">
            <span v-if="text.priority == 1">上移</span>
            <a v-else @click.stop="RuleMove('up', text)">上移</a>
            <!-- <a @click.stop="RuleMove('up', text)">上移</a> -->
            <a-divider type="vertical" />
            <a @click.stop="RuleMove('down', text)">下移</a>
            <a-divider type="vertical" />
            <a @click="edit(text)">编辑</a>
            <a-divider type="vertical" />
            <a @click.stop="RuleDisable(text)">{{ text.disabled ? '禁用' : '启用' }}</a>
            <a-divider type="vertical" />
            <a @click.stop="delRule(text)">删除</a>
          </span>
        </p-table>
      </p-card>
    </div>
    <edit-model
      ref="model"
      :visible="visible"
      @hidemodel="hidemodel"
      :title="title"
      :strategyType="strategyType"
      :items="strategyitem"
    ></edit-model>

    <p-modal
      :title="'新增规则'"
      width="50%"
      :visible="RuleTableVisible"
      :confirm-loading="confirmLoading"
      @ok="handleOkRuleTable"
      @cancel="RuleTableVisible = false"
      :maskClosable="false"
      :enlargeable="true"
      :draggable="true"
    >
      <p-grid-form
        :ref="tablecolumns.modalItems.ref"
        :span="8"
        :label-col="{ span: 9 }"
        :items="tablecolumns.modalItems.items"
      ></p-grid-form>
    </p-modal>
  </div>
</template>
<script>
import {
  RuleAdd,
  RuleDel,
  RuleDisableUpdate,
  StrategyEnableUpdate,
  RuleDown,
  RuleUp,
  MainTabledel,
  getWarehouseInfo,
  getCargoOwnerInfo,
} from '../../api'
import tablecolumns from './config/tableconfjg'
import model from './config/model'
import EditModel from './model.vue'
export default {
  name: 'MainTable',
  data() {
    return {
      title: '新增策略',
      strategy: {},
      strategyId: '',
      tablecolumns: tablecolumns(this),
      model: model(this),
      data: [],
      RuleTableVisible: false,
      MainTableremoteParams: {
        category: this.strategyType,
      },
      RuleTableremoteParams: {},
      RuleTabledata: [],
      confirmLoading: false,
      //   items: [],
      visible: false,
    }
  },
  props: {
    strategyType: {
      type: String,
      default: '',
    },
  },
  computed: {
    strategyitem() {
      return this.model.strategy.items
    },
  },
  components: {
    EditModel,
  },
  mounted() {},
  methods: {
    loadExtendData(data) {
      let wids = []
      let cargoids = []
      //   getCargoOwnerInfo
      if (data && data.length > 0) {
        data.forEach((x) => {
          wids.indexOf(x.warehouseId) == -1 && wids.push(x.warehouseId)
          cargoids.indexOf(x.cargoOwnerId) == -1 && cargoids.push(x.cargoOwnerId)
          x.warehouseName = 'loadding...'
          x.cargoOwnerName = 'loadding...'
        })
        if (wids.length > 0) {
          getWarehouseInfo({ warehouseIds: wids.join(',') }).then((d) => {
            if (d.success && d.data.length > 0) {
              d.data.forEach((z) => {
                data.forEach((x) => {
                  if (z.warehouseId == x.warehouseId) {
                    x.warehouseName = z.warehouseName
                  }
                })
              })
            }
          })
        }

        if (cargoids.length > 0) {
          getCargoOwnerInfo(cargoids).then((d) => {
            if (d.success) {
              //  d.data
              let list = Object.values(d.data)

              list.forEach((z) => {
                data.forEach((x) => {
                  if (z.cargoOwnerId == x.cargoOwnerId) {
                    x.cargoOwnerName = z.cargoOwnerName
                  }
                })
              })
            }
          })
        }
      }

      return data
    },
    async RuleMove(data, text) {
      let that = this
      let value = {
        id: text.id,
      }
      if (data == 'up') {
        let res = await RuleUp(value)
        if (res.success) {
          that.$message.success(`上移成功！${res.message}`)
          //   that.$refs[that.tablecolumns.RuleTable.ref].reload()
          that.RuleTableremoteParams = { ...that.RuleTableremoteParams }
        } else {
          that.$exception(res)
        }
      }
      if (data == 'down') {
        let res = await RuleDown(value)
        if (res.success) {
          that.$message.success(`下移成功！${res.message}`)
          //   that.$refs[that.tablecolumns.RuleTable.ref].reload()
          that.RuleTableremoteParams = { ...that.RuleTableremoteParams }
        } else {
          that.$exception(res)
        }
      }
    },
    //启用策略
    async StrategyEnable(value) {
      console.log(value)
      // StrategyEnableUpdate
      let that = this
      let data = {
        id: value.id,
      }
      let res = await StrategyEnableUpdate(data)
      if (res.success) {
        that.$message.success(`启用成功！${res.message}`)
        // that.$refs[that.tablecolumns.MainTable.ref].reload()
        that.MainTableremoteParams = { ...that.MainTableremoteParams }
      } else {
        that.$exception(res)
      }
    },
    async RuleDisable(value) {
      let that = this
      console.log(value)
      //禁用规则
      let data = {
        id: value.id,
        disable: !value.disabled,
      }
      let msg = value.disabled ? '禁用成功!' : '启用成功!'
      console.log(msg)
      let res = await RuleDisableUpdate(data)
      if (res.success) {
        that.$message.success(msg + res.message)
        // that.$refs[that.tablecolumns.RuleTable.ref].reload()

        that.RuleTableremoteParams = { ...that.RuleTableremoteParams }
      } else {
        that.$exception(res)
      }
    },
    //删除策略
    DelMainTable(value) {
      let that = this
      this.$confirm({
        title: '是否删除?',
        okText: '确认',
        cancelText: '取消',
        async onOk() {
          let res = await MainTabledel({ id: value.id })
          if (res.success) {
            that.$message.success(`删除成功！${res.message}`)
            // that.$refs[that.tablecolumns.MainTable.ref].reload()
            that.MainTableremoteParams = { ...that.MainTableremoteParams }
          } else {
            that.$exception(res)
          }
        },
      })
    },
    //删除规则
    delRule(value) {
      let that = this
      this.$confirm({
        title: '是否删除?',
        okText: '确认',
        cancelText: '取消',
        async onOk() {
          let res = await RuleDel({ id: value.id })
          if (res.success) {
            that.$message.success(`删除成功！${res.message}`)
            // that.$refs[that.tablecolumns.RuleTable.ref].reload()
            that.RuleTableremoteParams = { ...that.RuleTableremoteParams }
          } else {
            that.$exception(res)
          }
        },
      })
    },
    //添加策略
    AddStrategy(value) {
      this.visible = true
      if (value) {
        this.title = '编辑策略'
        this.$refs.model.setvalue(value)
      } else {
        this.title = '新增策略'
        this.$refs.model.resetFields()
      }
    },
    //点击策略表 查询规则表
    clickRow(event, index, value) {
      this.strategy = value
      this.RuleTableremoteParams = {
        strategyId: value.id,
      }
    },
    addRuleTable() {
      //添加规则
      this.RuleTableVisible = true
    },
    handleOkRuleTable() {
      let that = this
      this.$refs[this.tablecolumns.modalItems.ref].form.validateFields(async (err, values) => {
        if (!err) {
          let data = Object.assign({}, values, { strategyId: that.strategy.id })
          let res = await RuleAdd(data)
          if (res.success) {
            this.RuleTableVisible = false
            // this.$refs[this.tablecolumns.RuleTable.ref].reload()
            that.RuleTableremoteParams = { ...that.RuleTableremoteParams }
          } else {
            that.$exception(res)
          }
        }
      })
      //
    },
    edit(value) {
      console.log(value)
      let that = this
      let data = { value, strategy: that.strategy }
      this.$emit('back', false, { rule: value, strategy: that.strategy })
    },
    reload() {
      //   this.$refs[this.tablecolumns.MainTable.ref].reload()
      this.MainTableremoteParams = { ...this.MainTableremoteParams }
    },
    hidemodel(value) {
      this.visible = false
      if (value) {
        this.reload()
      }
    },
  },
}
</script>
