<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="销售日期" prop="saleDate">
        <el-date-picker clearable v-model="queryParams.saleDate" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择销售日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="客户名称" prop="custName">
        <el-input v-model="queryParams.custName" placeholder="请输入客户名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="客户电话" prop="custPhone">
        <el-input v-model="queryParams.custPhone" placeholder="请输入客户电话" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="销售人员" prop="salesper">
        <el-input v-model="queryParams.salesper" placeholder="请输入销售人员" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="检疫证号" prop="quaranNo">
        <el-input v-model="queryParams.quaranNo" placeholder="请输入检疫证号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="审批编号" prop="apprNo">
        <el-input v-model="queryParams.apprNo" placeholder="请输入审批编号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="总价" prop="price">
        <el-input v-model="queryParams.price" placeholder="请输入总价" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="技术员" prop="tech">
        <el-input v-model="queryParams.tech" placeholder="请输入技术员" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['sale:sale:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdateOrView"
          v-hasPermi="['sale:sale:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['sale:sale:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['sale:sale:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="saleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="id" />
      <el-table-column label="销售日期" align="center" prop="saleDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.saleDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="客户名称" align="center" prop="custName" />
      <el-table-column label="客户电话" align="center" prop="custPhone" />
      <el-table-column label="客户地址" align="center" prop="custAddr" />
      <el-table-column label="销售人员" align="center" prop="salesper" />
      <el-table-column label="检疫证号" align="center" prop="quaranNo" />
      <el-table-column label="审批编号" align="center" prop="apprNo" />
      <el-table-column label="总价" align="center" prop="price" />
      <el-table-column label="技术员" align="center" prop="tech" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdateOrView(scope.row, 'view')"
            v-hasPermi="['sale:sale:edit']">销售项目</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdateOrView(scope.row)"
            v-hasPermi="['sale:sale:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['sale:sale:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改销售主单对话框 -->
    <el-dialog :title="title" v-model="open" width="1200px" append-to-body>
      <el-form ref="saleRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="销售日期" prop="saleDate">
          <el-date-picker clearable v-model="form.saleDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择销售日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="客户名称" prop="custName">
          <el-input v-model="form.custName" placeholder="请输入客户名称" />
        </el-form-item>
        <el-form-item label="客户电话" prop="custPhone">
          <el-input v-model="form.custPhone" placeholder="请输入客户电话" />
        </el-form-item>
        <el-form-item label="客户地址" prop="custAddr">
          <el-input v-model="form.custAddr" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="销售人员" prop="salesper">
          <el-input v-model="form.salesper" placeholder="请输入销售人员" />
        </el-form-item>
        <el-form-item label="检疫证号" prop="quaranNo">
          <el-input v-model="form.quaranNo" placeholder="请输入检疫证号" />
        </el-form-item>
        <el-form-item label="审批编号" prop="apprNo">
          <el-input v-model="form.apprNo" placeholder="请输入审批编号" />
        </el-form-item>
        <el-form-item label="总价" prop="price">
          <el-input v-model="form.price" placeholder="请输入总价" />
        </el-form-item>
        <el-form-item label="技术员" prop="tech">
          <el-input v-model="form.tech" placeholder="请输入技术员" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-divider content-position="center">销售明细信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddDdSaleItem">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteDdSaleItem">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="ddSaleItemList" :row-class-name="rowDdSaleItemIndex"
          @selection-change="handleDdSaleItemSelectionChange" ref="ddSaleItem">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50" />
          <el-table-column label="明细类型" prop="itemType" width="150">
            <template #default="scope">
              <el-select v-model="scope.row.itemType" placeholder="请选择明细类型">
                <el-option v-for="dict in frozen_sale_item_type" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="胚胎编号或冻精号" prop="itemCode" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.itemCode" placeholder="请输入胚胎编号或冻精号" />
            </template>
          </el-table-column>
          <el-table-column label="数量" prop="qty" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.qty" placeholder="请输入数量" />
            </template>
          </el-table-column>
          <el-table-column label="单价" prop="unitPrice" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.unitPrice" placeholder="请输入单价" />
            </template>
          </el-table-column>
          <el-table-column label="所在液氮罐ID" prop="tankId" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.tankId" placeholder="请输入所在液氮罐ID" />
            </template>
          </el-table-column>
          <el-table-column label="所在提桶ID" prop="bucketId" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.bucketId" placeholder="请输入所在提桶ID" />
            </template>
          </el-table-column>
          <el-table-column label="所在冷冻架ID" prop="rackId" width="180">
            <template #default="scope">
              <el-input v-model="scope.row.rackId" placeholder="请输入所在冷冻架ID" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog :title="title" v-model="openView" width="1200px" append-to-body>
      <el-table :data="ddSaleItemList" :row-class-name="rowDdSaleItemIndex"
        @selection-change="handleDdSaleItemSelectionChange" ref="ddSaleItem">
        <el-table-column type="selection" width="50" align="center" disabled />
        <el-table-column label="序号" align="center" prop="index" width="50" />
        <el-table-column label="明细类型" prop="itemType" width="150">
          <template #default="scope">
            <el-select v-model="scope.row.itemType" placeholder="请选择明细类型" disabled>
              <el-option v-for="dict in frozen_sale_item_type" :key="dict.value" :label="dict.label"
                :value="dict.value"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="胚胎编号或冻精号" prop="itemCode" width="150" align="center" />
        <el-table-column label="数量" prop="qty" width="150" align="center" />

        <el-table-column label="单价" prop="unitPrice" width="150" align="center" />
        <el-table-column label="所在液氮罐ID" prop="tankId" width="150" align="center" />
        <el-table-column label="所在提桶ID" prop="bucketId" width="150" align="center" />
        <el-table-column label="所在冷冻架ID" prop="rackId" width="180" align="center" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup name="Sale">
  import { listSale, getSale, delSale, addSale, updateSale } from "@/api/frozen/sale"
  import { tr } from "date-fns/locale"

  const { proxy } = getCurrentInstance()
  const { frozen_sale_item_type } = proxy.useDict('frozen_sale_item_type')

  const saleList = ref([])
  const ddSaleItemList = ref([])
  const open = ref(false)
  const openView = ref(false)
  const loading = ref(true)
  const showSearch = ref(true)
  const ids = ref([])
  const checkedDdSaleItem = ref([])
  const single = ref(true)
  const multiple = ref(true)
  const total = ref(0)
  const title = ref("")

  const data = reactive({
    form: {},
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      saleDate: null,
      custName: null,
      custPhone: null,
      custAddr: null,
      salesper: null,
      quaranNo: null,
      apprNo: null,
      price: null,
      tech: null,
    },
    rules: {
      saleDate: [
        { required: true, message: "销售日期不能为空", trigger: "blur" }
      ],
      custName: [
        { required: true, message: "客户名称不能为空", trigger: "blur" }
      ],
      price: [
        { required: true, message: "总价不能为空", trigger: "blur" }
      ],
      tech: [
        { required: true, message: "技术员不能为空", trigger: "blur" }
      ],
    }
  })

  const { queryParams, form, rules } = toRefs(data)

  /** 查询销售主单列表 */
  function getList() {
    loading.value = true
    listSale(queryParams.value).then(response => {
      saleList.value = response.rows
      total.value = response.total
      loading.value = false
    })
  }

  // 取消按钮
  function cancel() {
    open.value = false
    reset()
  }

  // 表单重置
  function reset() {
    form.value = {
      id: null,
      saleDate: null,
      custName: null,
      custPhone: null,
      custAddr: null,
      salesper: null,
      quaranNo: null,
      apprNo: null,
      price: null,
      tech: null,
      remark: null,
      createBy: null,
      createTime: null
    }
    ddSaleItemList.value = []
    proxy.resetForm("saleRef")
  }

  /** 搜索按钮操作 */
  function handleQuery() {
    queryParams.value.pageNum = 1
    getList()
  }

  /** 重置按钮操作 */
  function resetQuery() {
    proxy.resetForm("queryRef")
    handleQuery()
  }

  // 多选框选中数据
  function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.id)
    single.value = selection.length != 1
    multiple.value = !selection.length
  }

  /** 新增按钮操作 */
  function handleAdd() {
    reset()
    open.value = true
    title.value = "添加销售主单"
  }

  /** 修改按钮操作 */
  function handleUpdateOrView(row, mode) {
    reset()
    const _id = row.id || ids.value
    getSale(_id).then(response => {
      form.value = response.data
      ddSaleItemList.value = response.data.ddSaleItemList
      if (mode === 'view') {
        openView.value = true
        title.value = "查看销售主单"
      } else {
        open.value = true
        title.value = "修改销售主单"
      }
    })
  }
  /** 提交按钮 */
  function submitForm() {
    proxy.$refs["saleRef"].validate(valid => {
      if (valid) {
        form.value.ddSaleItemList = ddSaleItemList.value
        if (form.value.id != null) {
          updateSale(form.value).then(response => {
            proxy.$modal.msgSuccess("修改成功")
            open.value = false
            getList()
          })
        } else {
          addSale(form.value).then(response => {
            proxy.$modal.msgSuccess("新增成功")
            open.value = false
            getList()
          })
        }
      }
    })
  }

  /** 删除按钮操作 */
  function handleDelete(row) {
    const _ids = row.id || ids.value
    proxy.$modal.confirm('是否确认删除销售主单编号为"' + _ids + '"的数据项？').then(function () {
      return delSale(_ids)
    }).then(() => {
      getList()
      proxy.$modal.msgSuccess("删除成功")
    }).catch(() => { })
  }

  /** 销售明细序号 */
  function rowDdSaleItemIndex({ row, rowIndex }) {
    row.index = rowIndex + 1
  }

  /** 销售明细添加按钮操作 */
  function handleAddDdSaleItem() {
    let obj = {}
    obj.itemType = ""
    obj.itemCode = ""
    obj.qty = ""
    obj.unitPrice = ""
    obj.tankId = ""
    obj.bucketId = ""
    obj.rackId = ""
    ddSaleItemList.value.push(obj)
  }

  /** 销售明细删除按钮操作 */
  function handleDeleteDdSaleItem() {
    if (checkedDdSaleItem.value.length == 0) {
      proxy.$modal.msgError("请先选择要删除的销售明细数据")
    } else {
      const ddSaleItems = ddSaleItemList.value
      const checkedDdSaleItems = checkedDdSaleItem.value
      ddSaleItemList.value = ddSaleItems.filter(function (item) {
        return checkedDdSaleItems.indexOf(item.index) == -1
      })
    }
  }

  /** 复选框选中数据 */
  function handleDdSaleItemSelectionChange(selection) {
    checkedDdSaleItem.value = selection.map(item => item.index)
  }

  /** 导出按钮操作 */
  function handleExport() {
    proxy.download('sale/sale/export', {
      ...queryParams.value
    }, `sale_${new Date().getTime()}.xlsx`)
  }

  getList()
</script>
