import {
  cancelChangeOrder,
  changeOrderDetailByUser,
  changeOrderPage,
  confirmChangeOrder, rejectChangeOrder, saveChangeOrder
} from "@/api/dev/deviceChangeOrderApi";
import {deviceChangeStatus, deviceChangeType} from "@/utils/enum";
import "@/store/getters";
import {genDeviceCode} from "@/api/dev/deviceInfoApi";
import deviceInfo from "@/views/dev/deviceInfo.vue";
import product from "@/views/basic/product/product.vue";
import {copyProperties} from "@/utils";


let query = {
  page: 1,
  limit: 10,
  changeOrderId: null,
  remark: null,
  deptCode: null,
  toDeptCode: null,
}
let detailQuery = {
  page: 1,
  limit: 10,
  orderId: null,
  type: null,
}

let createData = {
  type: deviceChangeType.CHANGE.key,
  toDeptCode: null,
  name: null,
  remark: null,
  items: []
}

let item = {
  deviceCode: null,
  productId: null,
  udi: null,
  batchNo: null,
  serialNo: null,
  productionDate: null,
  expireDate: null,
  nameCode: null,
  productName: null,
  zczbhhzbapzbh: null,
  measname: null,
  ggxh: null,
  supName: null,
  manufactory: null,
  editFlag: true,
}
export default {
  name: "deviceChangeOrder",
  props: {
    type: {
      required: true,
    }
  },
  components: {deviceInfo, product},
  computed: {
    deviceChangeStatus() {
      return deviceChangeStatus
    },
    deviceChangeType() {
      return deviceChangeType
    }
  },
  data() {
    return {
      cacheKey: null,
      hasOrderCache: false,
      locDeptCode: null,
      locDeptName: null,
      clickRow: null,
      showSearch: true,
      loading: false,
      query: {...query},
      list: [],
      total: 0,
      // =======详情========================================
      stepActive: null,
      processStatus: "success",
      detailLoading: false,
      detailQuery: {...detailQuery},
      detailList: [],
      detailTotal: 0,
      //========================================
      //创建变更单============================================
      fullScreenFlag: false,
      createActive: 0,
      showCreateDialog: false,
      oldType: null,
      createData: {...createData},
      itemMap: new Map(),
      itemList: [],
      createRule: {
        toDeptCode: [{
          required: true,
          validator: this.validToDeptCode,
          tigger: 'change',
          message: "目标部门不能为空"
        }],
      },
      chooseDeviceFlag: false,
      chooseProductFlag: false,
      //==================================================
    }
  },
  created() {
    let adminId = this.$store.getters.adminId
    this.cacheKey = "deviceChangeOrder" + this.type.key + adminId
    this.locDeptCode = this.$store.getters.locDeptCode
    this.locDeptName = this.$store.getters.locDeptName
    this.getList()
  },
  watch: {
    "createData.type": {
      handler(v, o) {
        if (o) {
          this.oldType = o
        }
      }
    },
    itemList(v, o) {
      this.parseItemMap()
    }
  },
  updated() {
    let data = window.localStorage.getItem(this.cacheKey)
    if (data == null) {
      this.hasOrderCache = false
    } else {
      this.hasOrderCache = true
    }
  },
  methods: {
    saveCache() {
      let data = window.localStorage.getItem(this.cacheKey)
      if (data == null) {
        data = {
          createActive: this.createActive,
          createData: this.createData,
          itemList: this.itemList
        }
        window.localStorage.setItem(this.cacheKey, JSON.stringify(data))
        this.showCreateDialog = false
      } else {
        this.$confirm("检测到已经挂起了一单，如继续挂起将会覆盖之前的单，是否继续", "提示", {
          confirmButtonText: "继续",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          data = {
            createActive: this.createActive,
            createData: this.createData,
            itemList: this.itemList
          }
          window.localStorage.setItem(this.cacheKey, JSON.stringify(data))
          this.showCreateDialog = false
        })
      }
    },
    saveForm() {
      if (this.itemList.length == 0) {
        this.$confirm(`请添加数据`, "提示", {
          confirmButtonText: "确定",
          type: "error",
        })
        return
      }
      if (this.createData.type == deviceChangeType.ADD.key) {
        let index = this.itemList.findIndex(i => !i.deviceCode || !i.productId);
        if (index != -1) {
          this.$confirm(`请检查第${index + 1}行的数据（是否有选择产品/是否有生成设备号）`, "提示", {
            confirmButtonText: "确定",
            type: "error",
          })
          return
        }
      } else {
        let index = this.itemList.findIndex(i => !i.deviceCode && !i.productId);
        if (index != -1) {
          this.$confirm(`请先移除空行,第${index + 1}行`, "提示", {
            confirmButtonText: "确定",
            type: "error",
          })
          return
        }
      }
      this.createData.items = this.itemList
      let loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      saveChangeOrder(this.createData).then(res => {
        loading.close()
        if (res.code != 20000) {
          this.$message.error(res.message)
          return
        }
        this.$message.success(res.message)
        this.showCreateDialog = false
        this.query = {...query}
        this.getList()
      }).catch(() => {
        loading.close()
      })
    },
    delDeviceRow(index) {
      this.itemList.splice(index, 1)
    },
    copyRow(index) {
      let data = {
        ...this.itemList[index],
        editFlag: true,
        batchNo: null,
        serialNo: null,
        productionDate: null,
        expireDate: null,
        udi: null
      }
      this.genCode(data)
      this.itemList.splice(index, 0, data)
    },
    batchCopyRow(index) {
      this.$prompt('请输入复制数量', '提示', {
        closeOnClickModal: false,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputType: Number,
        inputPlaceholder: '请输入复制数量',
        inputValidator: this.validNum,
      }).then(({value}) => {
        let loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        for (let i = 0; i < value; i++) {
          let data = {
            ...this.itemList[index],
            editFlag: true,
            batchNo: null,
            serialNo: null,
            productionDate: null,
            expireDate: null,
            udi: null
          }
          this.genCode(data)
          this.itemList.splice(index + i, 0, data)
        }
        loading.close()
      }).catch(() => {
      });
    },
    addDeviceRow() {
      if (this.createData.type == deviceChangeType.ADD.key) {
        let loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        genDeviceCode().then(res => {
          loading.close()
          if (res.code != 20000) {
            this.$message.error(res.message)
            return
          }
          let row = {...item, deviceCode: res.data}
          this.itemList.push(row);
        }).catch(e => {
          loading.close()
        })
      } else {
        let row = {...item}
        this.itemList.push(row);
      }
    },
    genCode(row) {
      let loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      genDeviceCode().then(res => {
        loading.close()
        if (res.code != 20000) {
          this.$message.error(res.message)
          return
        }
        row.deviceCode = res.data
      }).catch(e => {
        loading.close()
      })
    },
    openChoose(index) {
      if (this.createData.type == deviceChangeType.ADD.key) {
        this.chooseProductFlag = true
      } else {
        this.chooseDeviceFlag = true
      }
    },
    chooseDevice(row) {
      let data = copyProperties(row, item)
      let i = this.itemList.findIndex(i => i.deviceCode == data.deviceCode)
      if (i != -1) {
        this.$message.error("该设备已被选入,无法再次选择")
        return
      }

      this.itemList.push(data)

      this.chooseDeviceFlag = false
    },
    validNum(v) {
      let number = Number.parseInt(v);
      if (Number.isNaN(number)) {
        return "请输入大于0的数字，最大为100"
      }
      if (number <= 0 || number > 100) {
        return "请输入大于0的数字，最大为100"
      }
      return true
    },
    chooseProduct(row) {
      let loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      let data = copyProperties(row, item)
      data.editFlag = true
      this.genCode(data)
      data.productName = row.cpmctymc
      data.productId = row.id
      this.itemList.push(data)
      loading.close()
      this.chooseProductFlag = false
    },
    parseItemMap() {
      this.$nextTick(() => {
        if (this.itemList) {
          this.itemMap = this.itemList.reduce((accumulator, v) => {
            let key = `${v.productName}(${v.nameCode})`
            let count = accumulator.get(key)
            if (count == null) {
              accumulator.set(key, 1);
            } else {
              accumulator.set(key, count + 1);
            }
            return accumulator;
          }, new Map());
        } else {
          this.itemMap = new Map()
        }
      })
    },
    changeType(v) {
      if (this.itemList && this.itemList.length > 0) {
        this.$confirm("切换类型后已经选入的设备将会被清空，是否继续？", "提示", {
          confirmButtonText: "继续",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          this.itemList = []
        }).catch(() => {
          this.createData.type = this.oldType
        });
      }
    },
    changeActive(isNext) {
      if (isNext) {
        this.$refs.createForm.validate(flag => {
          if (flag) {
            this.createActive = 1
          }
        })
      } else {
        this.createActive = 0
      }
    },
    validToDeptCode(rule, value, callback) {
      if (this.createData.type == deviceChangeType.CHANGE.key && !value) {
        callback(new Error("目标部门不能为空"))
      }
      callback()
    },
    openCacheOrder() {
      let data = window.localStorage.getItem(this.cacheKey)
      if (data != null) {
        data = JSON.parse(data)
        this.fullScreenFlag = false
        this.createData = {...data.createData}
        this.createActive = data.createActive
        this.itemList = data.itemList
        this.oldType = null
        this.showCreateDialog = true
        window.localStorage.removeItem(this.cacheKey)
      }
    },
    openCreate() {
      this.fullScreenFlag = false
      this.createData = {...createData, type: this.type.key}
      this.createActive = 0
      this.oldType = null
      this.itemList = []
      this.showCreateDialog = true
    },
    confirm(row) {
      this.$prompt('请输入备注信息', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({value}) => {
        confirmChangeOrder(row.orderId, {remark: value}).then(res => {
          if (res.code != 20000) {
            this.$message.error(res.message)
            return
          }
          this.$message.success(res.message)
          this.query.page = 1
          this.getList()
          this.clickRow = null
        })
      })
    },
    reject(row) {
      this.$prompt('请输入备注信息', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({value}) => {
        rejectChangeOrder(row.orderId, {remark: value}).then(res => {
          if (res.code != 20000) {
            this.$message.error(res.message)
            return
          }
          this.$message.success(res.message)
          this.query.page = 1
          this.getList()
          this.clickRow = null
        })
      })
    },
    cancel(row) {
      this.$prompt('请输入备注信息', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({value}) => {
        cancelChangeOrder(row.orderId, {remark: value}).then(res => {
          if (res.code != 20000) {
            this.$message.error(res.message)
            return
          }
          this.$message.success(res.message)
          this.query.page = 1
          this.getList()
          this.clickRow = null
        })
      })
    },
    rowClick(row) {
      if (this.clickRow && row.orderId == this.clickRow.orderId) {
        return false
      }
      this.processStatus = "finish"
      if (row.status == deviceChangeStatus.WAIT_CONFIRM.key) {
        this.stepActive = 0
      } else {
        this.stepActive = 1
        if (row.status == deviceChangeStatus.FINISH.key) {
          this.processStatus = "success"
        }
        if (row.status == deviceChangeStatus.REJECT_CONFIRM.key) {
          this.processStatus = "error"
        }
        if (row.status == deviceChangeStatus.CANCEL.key) {
          this.processStatus = "error"
        }
      }
      this.clickRow = row
      this.detailQuery = {...detailQuery, orderId: row.orderId, type: row.type}
      this.getDetailList()
    },
    getDetailList() {
      this.detailLoading = true
      changeOrderDetailByUser(this.detailQuery).then(res => {
        this.detailLoading = false
        if (res.code != 20000) {
          this.$message.error(res.message)
          return
        }
        this.detailList = res.data.list || []
        this.detailTotal = res.data.total || 0
      }).catch(e => {
        this.detailLoading = false
      })
    },
    search() {
      this.query.page = 1
      this.getList()
    },
    onReset() {
      this.query = {...query}
      this.getList()
    },
    getList() {
      this.query.type = this.type.key
      this.loading = true
      changeOrderPage(this.query).then(res => {
        this.loading = false
        if (res.code != 20000) {
          this.$message.error(res.message)
          return
        }
        this.list = res.data.list || []
        this.total = res.data.total || 0
      }).catch(e => {
        this.loading = false
      })
    }
  }
}
