<template>

  <a-drawer
    title="物料检测标准"
    :width="1200"
    :visible="visible"
    :body-style="{ paddingBottom: '24px' }"
    @close="closeDraw"
  >
    <a-row :gutter="16" style="margin-bottom: 20px">
      <a-col :span="3">
        <a-button type="primary" @click="submitAll" :loading="loading" :disabled="submitDisable">
          保存
        </a-button>
      </a-col>
    </a-row>
    <a-table :columns="columns" :data-source="data" :pagination="false">
      <template
        v-for="col in ['weight']"
        :slot="col"
        slot-scope="text, record, index"
        :key="col"
      >
        <div>
          <a-input-number
            v-if="record.editable"
            style="margin: -5px 0"
            :value="text"
            :autoFocus="true"
            @change="e => handleChange(e, record.key, col)"
            :min="0"
            :step="0.1"
            :formatter="(value)=>{
      let reg = /^(-)*(\d+)\.(\d).*$/;
      return `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',').replace(reg,'$1$2.$3');
    }"
            :parser="(value)=>{
      let reg = /^(-)*(\d+)\.(\d).*$/;
      return value.replace(/\s?|(,*)/g, '').replace(reg,'$1$2.$3');
    }"
          />
          <template v-else>
            {{ text }}
          </template>
        </div>
      </template>
      <template
        v-for="col in ['limitMin']"
        :slot="col"
        slot-scope="text, record, index"
        :key="col"
      >
        <div>
          <a-input-number
            v-if="record.editable"
            style="margin: -5px 0"
            :value="text"
            @change="e => handleChange(e, record.key, col)"
            :min="0"
            :step="1"
            :autoFocus="true"
            :formatter="(value)=>{
              if (typeof value === 'string') {
                return !isNaN(Number(value)) ? value.replace(/^(0+)|[^\d]/g, '') : ''
              }else if (typeof value === 'number') {
                return !isNaN(value) ? String(value).replace(/^(0+)|[^\d]/g, '') : ''}
              else {
                return ''
              }}"/>
          <template v-else>
            {{ text }}
          </template>
        </div>
      </template>

      <template slot="required" slot-scope="text, record">
        <a-switch checked-children="是" un-checked-children="否" :autoFocus="true"
                  :checked="record.required === 0" @change="changeRequired(record)"
                  :loading="changeLoading"/>
      </template>

      <template slot="operation" slot-scope="text, record, index">
        <div class="editable-row-operations">
          <span v-if="record.editable">
            <a @click="() => save(record.key)">保存</a>
            <a-divider type="vertical"/>
            <a-popconfirm title="确定取消吗?" @confirm="() => cancel(record.key)">
              <a>取消</a>
            </a-popconfirm>
          </span>
          <span v-else>
            <a :disabled="editingKey !== ''" @click="() => edit(record.key)">编辑</a>
          </span>
        </div>
      </template>
      <template slot="sort" slot-scope="text, record, index">
        <a-tag color="pink" @click="up(index)" style="cursor: pointer"
               :class="index == 0 ? 'disabled' : '' ">
          <a-icon type="arrow-up"/>
        </a-tag>
        <a-tag color="blue" @click="down(index)" style="cursor: pointer"
               :class="index === data.length-1 ? 'disabled' : '' ">
          <a-icon type="arrow-down"/>
        </a-tag>
      </template>
    </a-table>


  </a-drawer>
</template>

<script>
import { getAction, postAction } from '/src/api/manage/manage'

export default {
  name: 'IntegrityCheckingDrawer',

  data() {
    return {
      visible: false,
      columns: [
        {
          title: '物料名称',
          dataIndex: 'materialLabel',
          align: 'center'
        },
        {
          title: '最低限制',
          dataIndex: 'limitMin',
          align: 'center',
          scopedSlots: {customRender: 'limitMin'}
        },
        {
          title: '评分占比',
          dataIndex: 'weight',
          align: 'center',
          scopedSlots: {customRender: 'weight'}
        },
        {
          title: '是否必填',
          dataIndex: 'required',
          align: 'center',
          scopedSlots: {customRender: 'required'}
        },
        {
          title: '排序',
          dataIndex: 'sort',
          align: 'center',
          scopedSlots: {customRender: 'sort'}
        },
        {
          title: '操作',
          dataIndex: 'operation',
          align: 'center',
          scopedSlots: {customRender: 'operation'}
        }
      ],
      data: [],
      cacheData: [],
      editingKey: '',
      sortChanged: false, // 判断排序是否改变，排序改变则在关闭的时候进行统一保存
      loading: false,
      loading2: false,
      id: '',
      changeLoading: false,
      submitDisable: false,
    }
  },
  methods: {
    submitAll() {
      let d = this.data
      let weight = 0
      for (let i in d) {
        weight += parseFloat(d[i].weight)
      }
      if (parseFloat(weight) !== 100) {
        this.$message.error('权重之和应为100')
        return
      }
      this.loading = true
      postAction('/serp/seoMarketPlan/saveTemplate', {
        checkList: JSON.stringify(d),
        planId: this.id
      }).then((res) => {
        this.loading = false
        if (res.code == 200) {
          this.$message.success('保存成功')
          this.showDrawer(this.id)
        } else {
          this.$message.error(res.message)
        }
      }).catch(e => {
        this.$message.error('保存数据失败！')
      })
    },
    showDrawer(id) {
      let that = this
      that.id = id
      getAction('/serp/seoMarketPlan/integrityChecking?planId=' + id).then((res) => {
        if (res.success) {
          that.data = res.result
          for (let i = 0; i < that.data.length; i++) {
            let item = that.data[i]
            item.key = item.id
          }
          that.cacheData = that.data.map(item => ({...item}))
        }
      }).catch(e => {
        this.$message.warning('获取数据失败！')
      })
      this.visible = true
    },
    closeDraw() {
      let that = this
      that.visible = false
      that.data = []
      that.cacheData = []
      that.sortChanged = false
      that.record = {}
    },
    handleChange(value, key, column) {
      const newData = [...this.data]
      const target = newData.filter(item => key === item.key)[0]
      if (target) {
        target[column] = value == null ? '' : value
        this.data = newData
      }
    },
    edit(key) {
      const newData = [...this.data]
      const target = newData.filter(item => key === item.key)[0]
      this.editingKey = key
      if (target) {
        target.editable = true
        this.data = newData
      }
      this.submitDisable = true
    },
    save(key) {
      const newData = [...this.data]
      const newCacheData = [...this.cacheData]
      const target = newData.filter(item => key === item.key)[0]
      const targetCache = newCacheData.filter(item => key === item.key)[0]
      if (target && targetCache) {
        delete target.editable
        this.data = newData
        Object.assign(targetCache, target)
        this.cacheData = newCacheData
      }
      this.editingKey = ''
      this.submitDisable = false
    },
    cancel(key) {
      const newData = [...this.data]
      const target = newData.filter(item => key === item.key)[0]
      this.editingKey = ''
      if (target) {
        Object.assign(target, this.cacheData.filter(item => key === item.key)[0])
        delete target.editable
        this.data = newData
      }
      this.submitDisable = false
    },
    up(index) {
      let that = this
      if (that.editingKey !== '') {
        that.$message.warn('请先完成编辑！')
        return
      }
      if (index === 0) {
        return
      }

      that.sortChanged = true

      // 修改展示顺序
      let data2 = that.data
      let temp1 = data2[index]
      data2[index] = data2[index - 1]
      data2[index - 1] = temp1
      that.cacheData = data2.map(item => ({...item}))
      that.data = that.cacheData
    },
    down(index) {
      let that = this
      if (that.editingKey !== '') {
        that.$message.warn('请先完成编辑！')
        return
      }
      if (index === that.data.length - 1) {
        return
      }
      that.sortChanged = true
      // 修改展示顺序
      let data2 = that.data
      let temp1 = data2[index]
      data2[index] = data2[index + 1]
      data2[index + 1] = temp1
      that.cacheData = data2.map(item => ({...item}))
      that.data = that.cacheData
    },

    changeRequired(record) {
      let that = this
      that.changeLoading = true
      postAction('/materialcollect/changeRequired?id=' + record.id + '&planId=' + record.planId).then((res) => {
        if (res.success) {
          that.$message.success(res.result)
          that.showDrawer(that.id)
        } else {
          that.$message.error(res.message)
        }
        that.changeLoading = false
      })
    },


  }
}
</script>
<style lang="less" scoped>
.ant-tag.disabled {
  cursor: no-drop !important;
  opacity: 0.3;
}
</style>
