import {
  cancelChangeOrder,
  changeOrderDetailByUser,
  changeOrderPage,
  confirmChangeOrder, delDraftOrder, rejectChangeOrder, saveChangeOrder, saveDraftOrder,
  generateOrderId,delOrderItem,entryOrderItem,updateOrderItem,entryOrderItemChange
} from "@/api/dev/deviceChangeOrderApi";
import {deviceChangeStatus, deviceChangeType,ApprovalFlowEnum} from "@/utils/enum";
import "@/store/getters";
import {genDeviceCode} from "@/api/dev/deviceInfoApi";
import deviceInfo from "@/views/dev/deviceInfo.vue";
import product from "@/views/purchase/purApply/purOrderSelectProduct";
import {copyProperties} from "@/utils";
import deviceModifyDialog from "@/views/dev/devInfoEdit.vue";
import deptDeviceDetail from "@/views/dev/DeptDeviceDetail.vue";
import dialogDeviceInvProduct from "@/views/dev/DialogDeviceSelectInvProduct.vue";
import dialogDeviceSelectAdd from "@/views/dev/DialogDeviceSelectAdd.vue";
import fa from "element-ui/src/locale/lang/fa";
import approvalFlowDetail from "@/components/ApprovalFlow/deviceChangeOrderDestroy";

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,
  deptCode: null,
  billNo: null,
  destroyType: 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,
  supId: null,
  manufactory: null,
  editFlag: true,
}
export default {
  name: "deviceChangeOrder",
  // dicts: ['device_source_type'],
  props: {
    type: {
      required: true,
    }
  },
  components: {deviceInfo, product, deviceModifyDialog,deptDeviceDetail,dialogDeviceInvProduct,dialogDeviceSelectAdd,approvalFlowDetail},
  computed: {
    deviceChangeStatus() {
      return deviceChangeStatus
    },
    deviceChangeType() {
      return deviceChangeType
    }
    ,
    ApprovalFlowEnum() {
      return ApprovalFlowEnum
    }
  },
  data() {
    return {
      addDetailQuery:{
        total:0,
        page:10,
        limit:1
      },
      cacheKey: null,
      hasOrderCache: false,
      locDeptCode: null,
      locDeptName: null,
      clickRow: null,
      showSearch: true,
      loading: false,
      query: {...query},
      approvalFlowDetailVisible:false,
      idQuery: {  },
      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: [],
      itemAddList: [],
      createRule: {
        toDeptCode: [{
          required: true,
          validator: this.validToDeptCode,
          tigger: 'change',
          message: "目标部门不能为空"
        }],
        deptCode: [{
          required: true,
          validator: this.validDeptCode,
          tigger: 'change',
          message: "操作部门不能为空"
        }],
      },
      chooseDeviceFlag: false,
      chooseProductFlag: false,
      selectInvProductVisible: false,
      selectDeviceAddVisible: false,
      deviceInfoFlag: false,
      createTitle: "设备登记",
      curDevRow: null,
      flagRemark: null,
      invQueryData: {
        invCode: null,
      },
      thisData: {},
      draftLoading: false,
      submitLoading: false,
      //==================================================

    }
  },
  created() {

    let adminId = this.$store.getters.adminId
    this.cacheKey = "deviceChangeOrder" + this.type.key + adminId
    this.locDeptCode = this.$store.getters.locDeptCode
    this.createData.deptCode = this.$store.getters.locDeptCode
    this.locDeptName = this.$store.getters.locDeptName

    if (this.type == deviceChangeType.ADD) {
      this.createTitle = "设备登记";
    } else if (this.type == deviceChangeType.CHANGE) {
      this.createTitle = "设备变更";
    } else if (this.type == deviceChangeType.DESTROY) {
      this.createTitle = "设备移除";
    }

    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: {
    closeDialog() {
      this.approvalFlowDetailVisible = false;
      this.getList()
    },
    handleClose() {
      this.approvalFlowDetailVisible = false;
      this.getList()
    },
    updateItem() {
      this.dict.type.device_source_type.forEach((item, index) => {
        if (this.createData.sourceType == item.value) {
          console.log(item)
          this.flagRemark = item.raw.remark
        }
      });
    },
    saveCache() {
      if (this.itemList.length == 0) {
        this.$confirm(`请添加数据`, "提示", {
          confirmButtonText: "确定",
          type: "error",
        })
        return
      }
      if (this.createData.type == deviceChangeType.ADD.key) {

      } else if (this.createData.type == deviceChangeType.CHANGE.key){

      }else if (this.createData.type == deviceChangeType.DESTROY.key){
        if (this.createData.destroyType == null){
          this.$message.warning("请选择移除类型后在立即提交")
          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)'
      });
      this.draftLoading = true
      saveDraftOrder(this.createData).then(res => {
        this.draftLoading = false
        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(() => {
        this.draftLoading = false
        loading.close()
      })

    },
    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 if (this.createData.type == deviceChangeType.CHANGE.key){
        let index = this.itemList.findIndex(i => !i.deviceCode && !i.productId);
        if (index != -1) {
          this.$confirm(`请先移除空行,第${index + 1}行`, "提示", {
            confirmButtonText: "确定",
            type: "error",
          })
          return
        }
      }else if (this.createData.type == deviceChangeType.DESTROY.key){
        if (this.createData.destroyType == null){
          this.$message.warning("请选择移除类型后在立即提交")
          return
        }
        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)'
      });
      this.submitLoading = true
      saveChangeOrder(this.createData).then(res => {
        this.submitLoading = false
        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(() => {
        this.submitLoading = false
        loading.close()
      })
    },
    //移除设备
    delDeviceRow(deviceCode) {
      //判断是否最后一条
      if (this.detailList.length == 1){
        this.$message.error("请注意，最后一条明细不可单独删除；如需删除，请直接删除整个单据。");
        return
      }

      delOrderItem(deviceCode).then(res => {
        if (res.code != 20000) {
          this.$message.error(res.message)
          return
        }
        this.getDetailList()
        this.$message.success(res.message)
      }).catch(() => {
      })

    },

    //编辑设备
    editDeviceRow(row) {
      this.curDevRow = row;
      this.deviceInfoFlag = true;
    },

    //设备编辑保存
    editSaveDev(row) {
      // this.curDevRow = row;
      // console.log(this.curDevRow)
      updateOrderItem(this.curDevRow).then(res => {
        if (res.code != 20000) {
          this.$message.error(res.message)
          return
        }
        this.getDetailList()
        this.$message.success(res.message)
      })
      // this.deviceInfoFlag = false;
    },
    copyRow(row) {
      this.itemAddList = []
      this.itemAddList.push(row)

      entryOrderItem(this.itemAddList).then(res => {
        if (res.code != 20000) {
          this.$message.error(res.message)
          return
        }
        this.getDetailList()
        this.$message.success(res.message)
      })
    },
    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()
      })
    },
    closeDialogC2(rData) {
      this.selectInvProductVisible = false;
      if (this.$isNotBlank(rData)) {
        this.codeFormData.code = rData;
        this.addCode();
        // this.codeFormData.code = null;
      }

      // this.refreshCodesPanel()
    },
    openChoose(index) {
      //如果orderId 空 就先生成
      if (this.createData.orderId == null){
        generateOrderId(this.createData).then(res => {
          if (res.code != 20000) {
            return
          }
          this.createData.orderId = res.data
          this.detailQuery.orderId = res.data
        }).catch(e => {
        })
      }
      if (index == 1) {
        this.chooseProductFlag = true
      }else if (index == 2) {
        this.selectInvProductVisible = true
      }else if (index == 3) {
        this.selectDeviceAddVisible = 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(lists) {
      let loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      this.itemAddList = []
      for (let row of lists) {
        let data = copyProperties(row, item)
        data.editFlag = true
        data.orderId = this.createData.orderId
        // if(!row.deviceCode){
        //   this.genCode(data)
        // }
        data.productName = row.cpmctymc
        data.productId = row.id
        data.sourceType = this.createData.sourceType
        this.itemAddList.push(data)
      }
      if (this.itemAddList.length > 0){
        if (this.type == deviceChangeType.ADD) {
          entryOrderItem(this.itemAddList).then( res =>{
            if (res.code != 20000) {
              this.$message.error(res.message)
              return
            }
            this.getDetailList()
            this.chooseProductFlag = false
            this.selectInvProductVisible = false
            this.selectDeviceAddVisible = false
            this.$message.success(res.message)
          })
        } else if (this.type == deviceChangeType.CHANGE) {
          entryOrderItemChange(this.itemAddList).then( res =>{
            if (res.code != 20000) {
              this.$message.error(res.message)
              return
            }
            this.getDetailList()
            this.chooseProductFlag = false
            this.selectInvProductVisible = false
            this.selectDeviceAddVisible = false
            this.$message.success(res.message)
          })
        } else if (this.type == deviceChangeType.DESTROY) {
          entryOrderItemChange(this.itemAddList).then( res =>{
            if (res.code != 20000) {
              this.$message.error(res.message)
              return
            }
            this.getDetailList()
            this.chooseProductFlag = false
            this.selectInvProductVisible = false
            this.selectDeviceAddVisible = false
            this.$message.success(res.message)
          })
        }
      }
      loading.close()
    },
    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()
    },
    validDeptCode(rule, value, callback) {
      if (!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.createData.deptCode = this.$store.getters.locDeptCode
      this.createActive = 0
      this.oldType = null
      this.itemList = []
      this.showCreateDialog = true
    },

    /**
     * 编辑单据
     */
    openEdit(row) {
      this.fullScreenFlag = false
      // this.createData = {...createData, type: this.type.key}

      this.createData = row
      this.createActive = 0
      this.oldType = null
      this.itemList = []
      this.showCreateDialog = true
      this.getDetailList()
    },

    /**
     * 删除单据
     * @param row
     */
    delOrder(row) {
      this.$confirm("确定删除该单据？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        delDraftOrder({"orderId": row.orderId}).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
        })
      })

    },

    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
        })
      })
    },
    showApprovalFlowDetail(row) {
      this.idQuery = row
      this.approvalFlowDetailVisible = true;
    },
    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
      if ( this.detailQuery.type == null){
        this.detailQuery.type = this.type.key
      }
      console.log(this.detailQuery)
      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
        this.itemList = this.detailList
      }).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
      })
    }
  }
}
