<template>
  <Mask :width="1200" :is-show="isShow" @close="exit"
        title="编辑" :height="720" :show-footer="true">
    <div class="edit-panel" v-loading="isLoading" element-loading-text="正在保存......">
      <div class="top">
        <el-form :model="inventory_order_data" label-position="top" ref="orderForm">
          <el-row>
            <el-col :span="6">
              <el-form-item label="订单编号">
                <div style="width: 234px;">
                  <span class="order-info">{{ inventory_order_data.code }}</span>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="采购人">
                <el-select
                    v-if="orderInfoIsEdit"
                    v-model="inventory_order_data.managerUserId"
                    placeholder="选择采购人"
                    clearable
                    style="width: 240px"
                >
                  <el-option
                      v-for="item in managerUserList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                  />
                </el-select>
                <span style="width: 234px;" class="order-info" v-else>{{ inventory_order_data.managerUserName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item prop="purchaseDate" label="采购日期">
                <el-date-picker
                    v-model="inventory_order_data.purchaseDate"
                    type="date"
                    placeholder="选择一个创建日期"
                    size="default"
                    value-format="YYYY-MM-DD"
                    v-if="orderInfoIsEdit"
                    style="width: 234px;"
                />
                <span style="width: 234px;" class="order-info" v-else>{{ inventory_order_data.purchaseDate }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item prop="shippingCode" label="货单号">
                <el-input v-model="inventory_order_data.shippingCode" v-if="orderInfoIsEdit"></el-input>
                <span class="order-info" v-else>{{ inventory_order_data.shippingCode }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item prop="invoiceCode" label="发票号">
                <el-input style="width: 234px;" v-model="inventory_order_data.invoiceCode"
                          v-if="orderInfoIsEdit"></el-input>
                <span style="width: 234px;" class="order-info" v-else>{{ inventory_order_data.invoiceCode }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item prop="supplierId" label="供应商" style="margin-bottom: 0">
                <el-select v-if="orderInfoIsEdit" style="width: 196px;margin-right: 10px"
                           v-model="inventory_order_data.supplierId"
                           placeholder="请选择供应商">
                  <el-option
                      v-for="item in supplier_list"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                  />
                </el-select>
                <div v-if="orderInfoIsEdit" class="default-btn"
                     style="
                     height: 32px;
                     width: 32px;
                     line-height: 32px;
                     border: 1px solid rgb(192, 196, 204);
                      background-color: #fff;"
                     @click="addSupplier">
                  <el-icon style="color: rgb(192, 196, 204)">
                    <Plus/>
                  </el-icon>
                </div>
                <span style="width: 234px;" class="order-info"
                      v-if="!orderInfoIsEdit">{{ inventory_order_data.supplierName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="备注" style="width: 234px">
                <el-input style="width: 234px;" v-model="inventory_order_data.remark" v-if="orderInfoIsEdit"/>
                <span style="width: 234px;" class="order-info" v-else>{{ inventory_order_data.remark }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="操作">
                <span class="default-btn form-item" @click="saveOrderEdit" v-if="orderInfoIsEdit">保存</span>
                <span class="default-btn form-item" @click="editOrder" v-else>编辑</span>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="table_content">
        <div class="add_goods">
          <span class="default-btn" @click="changeShowGoodSearch">{{ showGoodSearch ? '取消' : '添加药品' }}</span>
          <div class="search">
            <GoodsSearch v-if="showGoodSearch" @selectCallBack="goodsSelectCallBack"></GoodsSearch>
          </div>
        </div>
        <el-table :data="table_list" style="width: 100%" height="250"
                  :header-cell-style="{ backgroundColor: '#F1F5FB' }">
          <el-table-column prop="name" label="药品名称" width="180" show-overflow-tooltip/>
          <el-table-column label="售价" prop="unitPrice" width="80" show-overflow-tooltip>
          </el-table-column>
          <el-table-column label="单位" prop="packagingUnit" width="80" show-overflow-tooltip>
          </el-table-column>
          <el-table-column label="数量" width="110" show-overflow-tooltip>
            <template #default="scope">
              <el-input-number
                  v-model="scope.row.wholeNumber"
                  :min="1"
                  size="small"
                  controls-position="right"
                  style="width: 80px"
                  @change="getTotalPrice"
                  v-if="scope.row.isEdit"
              />
              <span v-else>{{ scope.row.wholeNumber }}</span>
            </template>

          </el-table-column>
          <el-table-column label="进价" width="110" show-overflow-tooltip>
            <template #default="scope">
              <el-input-number
                  v-model="scope.row.purchaseUnitPrice"
                  :min="1"
                  size="small"
                  controls-position="right"
                  style="width: 80px"
                  @change="getTotalPrice"
                  v-if="scope.row.isEdit"
              />
              <span v-else>{{ scope.row.purchaseUnitPrice }}</span>
            </template>
          </el-table-column>
          <el-table-column label="生产批号" width="150" prop="productionBatchCode" show-overflow-tooltip>
            <template #default="scope">
              <el-input v-model="scope.row.productionBatchCode" placeholder="生产批号" style="width: 100px" size="small"
                        v-if="scope.row.isEdit"/>
              <span v-else>{{ scope.row.productionBatchCode }}</span>
            </template>
          </el-table-column>
          <el-table-column label="生产日期" width="140" show-overflow-tooltip>
            <template #default="scope">
              <el-date-picker
                  v-model="scope.row.productionDate"
                  type="date"
                  placeholder="生产日期"
                  size="small"
                  style="width: 100px;"
                  value-format="YYYY-MM-DD"
                  v-if="scope.row.isEdit"
              />
              <span v-else>{{ scope.row.productionDate }}</span>
            </template>

          </el-table-column>
          <el-table-column label="有效日期" width="140" show-overflow-tooltip>
            <template #default="scope">
              <el-date-picker
                  v-model="scope.row.expiryDate"
                  type="date"
                  placeholder="有效日期"
                  size="small"
                  style="width: 100px;"
                  value-format="YYYY-MM-DD"
                  v-if="scope.row.isEdit"
              />
              <span v-else>{{ scope.row.expiryDate }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" show-overflow-tooltip>
            <template #default="scope">
              <span class="default-btn table-item" @click="addOneGoods(scope.row)"
                         v-if="!scope.row.id&&scope.row.isEdit">保存
              </span>
              <span class="default-btn table-item" @click="removeTableRow(scope.row)" v-if="!scope.row.id">移除
              </span>
              <span  class="default-btn table-item" @click="saveGoodEdit(scope.row)"
                         v-if="scope.row.id&&scope.row.isEdit">保存
              </span>
              <span class="default-btn table-item" @click="openGoodEdit(scope.row)"
                         v-if="scope.row.id&&!scope.row.isEdit">编辑
              </span>
              <span class="default-btn table-item" @click="returnableOne(scope.row.id)" v-if="scope.row.id">退货
              </span>
            </template>
          </el-table-column>

        </el-table>
      </div>
    </div>
    <template #footer>
      <div class="bottom">
        <div class="totalPrice">
          订单总金额：<span style="color: #FF282E;font-size: 12px">￥</span><span
            style="color: #FF282E">{{ inventory_order_data.totalPrice.toFixed(2) }}</span>
        </div>
        <div class="btn">
          <span class="default-btn" @click="returnableAll()">整单退货</span>
          <span class="default-btn" @click="exit">关闭</span>
        </div>
      </div>
    </template>
  </Mask>

  <AddSupplier ref="addSupplierRef" @close="getSupplierList"></AddSupplier>
  <Mask :is-show="is_add">
    <Edit ref="editRef" @close="is_add = false;"/>
  </Mask>
</template>

<script lang="ts" setup>
import {nextTick, onMounted, ref, watch} from 'vue'
import {post} from '@/utils/request.ts'
import Edit from "@/components/inventory/goods/Edit.vue";
import Mask from "@/components/common/Mask.vue";
import {ElMessage, ElMessageBox} from "element-plus";
import GoodsSearch from "@/components/inventory/GoodsSearch.vue";
import CloseBtn from "@/components/CloseBtn.vue";
import AddSupplier from "@/components/inventory/supplier/AddSupplier.vue";
import {Plus} from "@element-plus/icons-vue"

const props = defineProps({
  code: {
    type: String,
    default: ""
  }
})
const isLoading = ref(false)
const orderInfoIsEdit = ref(false)
const showGoodSearch = ref(false)
const changeShowGoodSearch = () => {
  showGoodSearch.value = !showGoodSearch.value
}
let inventory_order_data: any = ref({
  code: null,
  userId: 1,
  supplierId: 1,
  remark: null,
  managerUserId: null,
  kindConut: 0,
  totalPrice: 0,
})
const editOrder = () => {
  orderInfoIsEdit.value = true
}
const openGoodEdit = (row: any) => {
  row.isEdit = true
}
const saveGoodEdit = (row: any) => {
  const list = [];
  list.push(row);
  isLoading.value = true
  post("inventory/goods/update", {list: list})
      .then((res) => {
        row.isEdit = false
        getOrderDetail()
        emit('updateOrderDetail')
        isLoading.value = false
      })

}
const returnableOne = (id: any) => {
  const list: number[] = [];
  list.push(id);
  ElMessageBox.confirm(
      `确定要退货吗？`,
      'Warning',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
    returnableDo(list);
  })

}
const returnableAll = () => {
  const list: number[] = [];
  table_list.value.forEach((item: any) => {
    list.push(item.id);
  });
  ElMessageBox.confirm(
      `确定要对该订单的所以药品进行退货吗？`,
      'Warning',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
    returnableDo(list);
  })
}
const returnableDo = (idList: any) => {
  isLoading.value = true
  post("inventory/order/returnable", {idList: idList}).then((res) => {
    getOrderDetail()
    emit('updateOrderDetail')
    isLoading.value = false
  })
}
const saveOrderEdit = () => {
  isLoading.value = true
  post("inventory/order/update", {inventoryOrder: inventory_order_data.value}).then((res) => {
    orderInfoIsEdit.value = false
    getOrderDetail()
    emit('updateOrderDetail')
    isLoading.value = false
  })

}
const isShow = ref<any>(false)
const code = ref<any>('')
const init = (e: any) => {
  code.value = e
  isShow.value = true
  getSupplierList()
  getManagerUserList()
  getOrderDetail()

}
const getTotalPrice = () => {
  let totalPrice = 0;
  table_list.value.forEach((item: any) => {
    totalPrice += item.purchaseUnitPrice * item.wholeNumber
  })
  inventory_order_data.value.totalPrice = totalPrice;
}
const emit = defineEmits(['close', 'updateOrderDetail'])
let exit = () => {
  isShow.value = false
  emit('close')
}
const table_list: any = ref([])
const findIndexForTableList = (goodId: any) => {
  return table_list.value.findIndex((item: any) => item.goodId === goodId);
}
const is_add = ref(false)
const editRef = ref<InstanceType<typeof Edit>>();
const supplier_list: any = ref([])

const removeTableRow = (row: any) => {
  //根据row.goodId删除table_list中的数据
  let index = findIndexForTableList(row.goodId);
  if (index != -1) {
    table_list.value.splice(index, 1);
  }
}

const getSupplierList = () => {
  const query = {
    turn: 1
  }
  post("inventory/supplier/list", {query: query}).then((res: any) => {
    supplier_list.value = res.list
  })
}
const getOrderDetail = () => {
  post("inventory/order/detail", {code: code.value}).then((res: any) => {
    inventory_order_data.value = res.inventoryOrder
    table_list.value = res.inventoryOrderGoodsList
  })
}
const addOneGoods = (row: any) => {
  const data = JSON.parse(JSON.stringify(row));
  data.inventoryOrderCode = inventory_order_data.value.code;
  if (!checkValue(data)) {
    return
  }
  isLoading.value = true
  post("inventory/order/addOneGoods", {data: data}).then(
      (res: any) => {
        getOrderDetail()
        emit('updateOrderDetail')
        isLoading.value = false
      }
  )
}
const managerUserList: any = ref([])
const getManagerUserList = () => {
  post("manager/user/list", {}).then((res: any) => {
    managerUserList.value = res
  })
}

const checkValue = (data: any) => {
  let msg = null;
  if (data.wholeNumber == 0) {
    msg = "采购药品数量不能为0"
  }
  if (data.productionBatchCode == null || data.productionBatchCode == "") {
    msg = "生产批号不能为空"
  }
  if (!data.productionDate && data.productionDate == null) {
    msg = "生产日期不能为空"
  }
  if (!data.expiryDate && data.expiryDate == null) {
    msg = "有效日期不能为空"
  }
  if (msg != null) {
    ElMessage({
      message: msg,
      type: 'warning',
      plain: true,
    })
    return false
  }
  return true
}
const goodsSelectCallBack = (inventory: any) => {
  if (findIndexForTableList(inventory.goodId) != -1) {
    return
  }
  inventory.isEdit = true
  table_list.value.push(inventory);
  setTimeout(() => {
    changeShowGoodSearch()
    getTotalPrice()
  }, 200)
}
const addSupplierRef = ref();
const addSupplier = () => {
  nextTick(() => {
    addSupplierRef.value?.addInit()
  })

}
defineExpose({init})
</script>
<style scoped lang="scss">
.link {
  cursor: pointer;
  font-size: 12px;
  color: #2e7eb3;
}


.line {
  margin-right: 10px;

  .item {
    display: inline-block;
    width: 200px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;

    span {
      color: #999;
    }
  }

  .name {
    width: 300px;
  }

  .producer {
    width: 300px;
  }

  .unitPrice, .purchaseUnitPrice {
    width: 160px;
  }
}

.active {
  background-color: red;
}

.edit-panel {
  height: 562px;
  padding: 24px 24px 0;
  display: flex;
  flex-direction: column;

  .top {
    height: 180px;
  }

  .table_content {
    flex: 1;
    margin-top: 24px;
    display: flex;
    flex-direction: column;

    .add_goods {
      height: 90px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-weight: 800;
      font-size: 18px;
      color: #333333;
      font-style: normal;

      .search {
        width: 50%;
      }
    }
  }
}

.bottom {
  height: 86px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 400;
  font-size: 22px;
  color: #333333;
  font-style: normal;
  background: #fff;
  box-shadow: 0px -2 4px 0px rgba(0, 0, 0, 0.1);
  border-radius: 0 0 8px 8px;
}

.error {
  background-color: #F00;
}

.bottom {
  padding: 0 24px;
  height: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 400;
  font-size: 22px;
  color: #333333;
  font-style: normal;
}

.order-info {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.btn {
  .default-btn {
    margin-right: 24px;

    &:last-child {
      margin-right: 0;
    }
  }
}
.form-item {
  width: 60px;
  height: 31px;
  line-height: 31px;
}
.table-item{
  width: 48px;
  height: 25px;
  line-height: 25px;
  font-size: 12px;
  margin-right: 10px;
  :last-child{
    margin-right: 0;
  }
}
</style>