<template>
  <div>
    <template>
      <el-dialog title="批量编辑" :close-on-click-modal="false" :visible.sync="visible" width="1000px" class="JNPF-dialog JNPF-dialog_center" lock-scroll>
        <div style="height: 60vh">
          <el-table v-loading="listLoading" :data="tableData" border height="50vh" @selection-change="handleSelectionChange" style="width: 100%">
            <el-table-column label="序号" align="center" width="50">
              <template slot-scope="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column
              :label="item.label"
              :align="item.align"
              :width="item.width"
              minWidth="155"
              v-for="(item, i) in columnList"
              :prop="String(item.propId)"
              :key="i"
              :sortable="item.sortable ? 'custom' : item.sortable"
            >
              <template slot-scope="scope">
                <el-date-picker
                  size="small"
                  v-if="item.jnpfKey === 'date' || item.jnpfKey === 'datetime'"
                  v-model="scope.row[item.propId]"
                  :type="item.jnpfKey"
                  :format="getFormat(item.propId, 'format')"
                  style="width: 100%"
                  :value-format="getvalueFormat(item.propId, 'value-format')"
                  placeholder="选择日期时间"
                  :disabled="getDisabled(item.propId)"
                  @change="itemChange(item.propId, item.label, item.jnpfKey, $event)"
                ></el-date-picker>
                <el-input
                  v-if="item.jnpfKey === 'comInput' || item.jnpfKey === 'numInput' || item.jnpfKey === 'textarea'"
                  v-model="scope.row[item.propId]"
                  :type="item.jnpfKey === 'comInput' || item.jnpfKey === 'textarea' ? 'text' : 'number'"
                  :disabled="getDisabled(item.propId)"
                  @change="itemChange(item.propId, item.label, item.jnpfKey, $event)"
                ></el-input>
                <el-select
                  v-if="item.jnpfKey === 'radio' || item.jnpfKey === 'select'"
                  :multiple="item.jnpfKey === 'checkbox'"
                  v-model="scope.row[item.propId]"
                  :disabled="getDisabled(item.propId)"
                  @change="itemChange(item.propId, item.label, item.jnpfKey, $event)"
                >
                  <el-option v-for="item in getOption(item.jnpfKey, item.propId)" :key="item.id" :label="item.fullName" :value="item.id"></el-option>
                </el-select>
                <el-select
                  v-if="item.jnpfKey === 'checkbox'"
                  :multiple="item.jnpfKey === 'checkbox'"
                  :disabled="getDisabled(item.propId)"
                  v-model="scope.row[item.propId]"
                  @change="itemChange(item.propId, item.label, item.jnpfKey, $event)"
                >
                  <el-option v-for="item in getOption(item.jnpfKey, item.propId)" :key="item.id" :label="item.fullName" :value="item.id"></el-option>
                </el-select>
                <el-switch
                  v-if="item.jnpfKey === 'switch'"
                  v-model="scope.row[item.propId]"
                  active-value="1"
                  inactive-value="0"
                  :disabled="getDisabled(item.propId)"
                  @change="itemChange(item.propId, item.label, item.jnpfKey, $event)"
                ></el-switch>
                <el-cascader
                  v-if="item.jnpfKey === 'cascader'"
                  v-model="scope.row[item.propId]"
                  :disabled="getDisabled(item.propId)"
                  :props="{ value: 'id', label: 'fullName', children: 'children' }"
                  :options="getOption(item.jnpfKey, item.propId)"
                  @change="itemChange(item.propId, item.label, item.jnpfKey, $event)"
                >
                </el-cascader>
              </template>
            </el-table-column>
          </el-table>
          <div style="margin-top: 9px; float: right">
            <el-button type="primary" size="mini" @click="visible = false">取消</el-button>
            <el-button :loading="btnLoading" type="primary" size="mini" @click="sumbitForm">确认</el-button>
          </div>
        </div>
        <el-dialog title="批量编辑设置" :close-on-click-modal="false" :visible.sync="NumberVisible" width="500px" class="JNPF-dialog JNPF-dialog_center" lock-scroll append-to-body>
          <el-form ref="NumberFrom" :model="NumberFrom" label-width="80px">
            <el-form-item label="编辑设置">
              <el-radio-group v-model="NumberFrom.type">
                <el-radio :label="1"
                  >应用相同
                  <el-tooltip effect="dark" content="将本次修改应用到本列所有数据" placement="top">
                    <i class="el-tooltip el-icon-question"></i>
                  </el-tooltip>
                </el-radio>
                <el-radio :label="2"
                  >均值
                  <el-tooltip effect="dark" content="本次修改值/所选批量编辑总条数" placement="top">
                    <i class="el-tooltip el-icon-question"></i>
                  </el-tooltip>
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item>
              <el-button @click="NumberVisible = false">取 消</el-button>
              <el-button type="primary" @click="setBatchEdit">确 认</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
      </el-dialog>
    </template>
  </div>
</template>

<script>
import { deepClone } from '@/utils'
import moment from 'moment/moment'
import { batchUpdateModel } from '@/api/onlineDev/visualDev'

export default {
  name: 'batchEdit',
  props: ['modelId'],
  data() {
    return {
      visible: false,
      listLoading: false,
      btnLoading: false,
      formData: {},
      oldData: [],
      tableData: [],
      columnList: [],
      idKey: null,
      NumberVisible: false,
      NumberFrom: {
        type: 1,
        id: null,
        value: null
      }
    }
  },
  methods: {
    init(formData, columnList, jsonData, idKey) {
      this.formData = deepClone(formData)
      this.columnList = columnList
      this.tableData = deepClone(jsonData)
      this.idKey = idKey
      this.visible = true
      this.columnList.forEach((val) => {
        this.tableData.forEach((v) => {
          //将不规范时间格式转换  避免提交报错
          if (val.jnpfKey === 'date' || val.jnpfKey === 'datetime') {
            v[val.propId] = moment(v[val.propId]).valueOf()
          }
        })
      })
      this.oldData = deepClone(this.tableData)
    },
    //获取时间值类型
    getFormat(id, type) {
      let str
      this.formData.fields.forEach((item) => {
        if (item.__vModel__ === id) {
          if (type === 'format') {
            str = item.format
          }
        }
      })
      return str
    },
    getvalueFormat(id, type) {
      let str
      this.formData.fields.forEach((item) => {
        if (item.__vModel__ === id) {
          if (type === 'value-format') {
            str = item['value-format']
          }
        }
      })
      return str
    },
    //获取下拉框值
    getOption(key, id) {
      let list = []
      if (key === 'radio' || key === 'select' || key === 'checkbox') {
        this.formData.fields.forEach((item) => {
          if (item.__vModel__ === id) {
            list = item.__slot__.options
          }
        })
      }
      if (key === 'cascader') {
        this.formData.fields.forEach((item) => {
          if (item.__vModel__ === id) {
            list = item.options
          }
        })
      }
      return list
    },
    //如有主键或计算字段之类 要禁用
    getDisabled(id) {
      let ItemDisabled = false
      this.formData.fields.forEach((item) => {
        if (item.__vModel__ === id) {
          ItemDisabled = item.disabled
        }
      })
      return ItemDisabled
    },
    //将每次修改后进行提示
    itemChange(id, label, jnpfKey, val) {
      this.$confirm(`是否将 ${label} 的修改应用到本列所有数据?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          //数字类型特殊处理
          if (jnpfKey === 'numInput') {
            this.NumberVisible = true
            this.NumberFrom.id = id
            this.NumberFrom.value = val
          } else {
            this.tableData.forEach((item, k) => {
              item[id] = val
            })
          }
        })
        .catch(() => {})
    },
    //数字类型批量处理
    setBatchEdit() {
      if (this.NumberFrom.type === 1) {
        this.tableData.forEach((item, k) => {
          item[this.NumberFrom.id] = this.NumberFrom.value
        })
      } else if (this.NumberFrom.type === 2) {
        this.tableData.forEach((item, k) => {
          item[this.NumberFrom.id] = Number(this.NumberFrom.value) / this.tableData.length
        })
      }
      this.NumberVisible = false
    },
    sumbitForm() {
      this.btnLoading = true
      //去空
      this.tableData.forEach((v, k) => {
        Object.keys(v).forEach((item) => {
          if (typeof v[item] === 'undefined' || v[item] === null) {
            delete v[item]
          }
        })
      })
      this.oldData.forEach((v, k) => {
        Object.keys(v).forEach((item) => {
          if (typeof v[item] === 'undefined' || v[item] === null) {
            delete v[item]
          }
        })
      })
      //整合
      let JsonData = this.tableData.map((item) => {
        return {
          data: this.getData(item),
          id: item[this.idKey],
          oldData: this.getOldData(item[this.idKey], this.idKey)
        }
      })
      batchUpdateModel(this.modelId, JsonData).then((res) => {
        if (res.data.code === 200) {
          this.$message({
            message: res.data.msg,
            type: 'success',
            duration: 1500
          })
          this.visible = false
          this.btnLoading = false
          this.$emit('batchEditDataList')
        } else {
          this.btnLoading = false
        }
      })
    },
    getData(item) {
      let obj = deepClone(item)
      delete obj[this.idKey]
      return JSON.stringify(obj)
    },
    getOldData(id, idKey) {
      let item
      this.oldData.forEach((i, k) => {
        if (i[idKey] === id) {
          item = i
        }
      })
      delete item[this.idKey]
      return JSON.stringify(item)
    },
    handleSelectionChange() {}
  }
}
</script>

<style scoped></style>
