<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryFormRef"  :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="客户姓名" prop="customerName">
        <el-input
          v-model="queryParams.customerName"
          placeholder="请输入客户姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="phonenumber">
        <el-input
          v-model="queryParams.phonenumber"
          placeholder="请输入手机号码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户性别" prop="sex">
        <el-select v-model="queryParams.sex" placeholder="请选择客户性别" clearable>
          <el-option
            v-for="dict in sys_user_sex"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客户生日" prop="birthday">
        <el-date-picker clearable
          v-model="queryParams.birthday"
          type="date"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          placeholder="请选择客户生日">
        </el-date-picker>
      </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="['demo:customer:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['demo:customer:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['demo:customer:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['demo:customer:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar  v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="customerList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="客户id" align="center" prop="customerId" />
      <el-table-column label="客户姓名" align="center" prop="customerName" />
      <el-table-column label="手机号码" align="center" prop="phonenumber" />
      <el-table-column label="客户性别" align="center" prop="sex">
        <template #default="scope">
          <dict-tag :options="sys_user_sex" :value="scope.row.sex"/>
        </template>
      </el-table-column>
      <el-table-column label="客户生日" align="center" prop="birthday" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.birthday, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <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
            type="text"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['demo:customer:edit']"
          >修改</el-button>
          <el-button
            type="text"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['demo:customer: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"
    />

    <!-- 添加或修改客户主表(mb)对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="customerRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="客户姓名" prop="customerName">
          <el-input v-model="form.customerName" placeholder="请输入客户姓名" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phonenumber">
          <el-input v-model="form.phonenumber" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="客户性别" prop="sex">
          <el-select v-model="form.sex" placeholder="请选择客户性别">
            <el-option
              v-for="dict in sys_user_sex"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户生日" prop="birthday">
          <el-date-picker clearable
            v-model="form.birthday"
            type="date"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            placeholder="请选择客户生日">
          </el-date-picker>
        </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="handleAddDemoGoods">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete"  @click="handleDeleteDemoGoods">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="demoGoodsList" :row-class-name="rowDemoGoodsIndex" @selection-change="handleDemoGoodsSelectionChange" ref="demoGoods">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="商品名称" prop="name" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.name" placeholder="请输入商品名称" />
            </template>
          </el-table-column>
          <el-table-column label="商品重量" prop="weight" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.weight" placeholder="请输入商品重量" />
            </template>
          </el-table-column>
          <el-table-column label="商品价格" prop="price" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.price" placeholder="请输入商品价格" />
            </template>
          </el-table-column>
          <el-table-column label="商品时间" prop="date" width="240">
            <template #default="scope">
              <el-date-picker clearable v-model="scope.row.date" type="date" value-format="YYYY-MM-DD" placeholder="请选择商品时间" />
            </template>
          </el-table-column>
          <el-table-column label="商品种类" prop="type" width="150">
            <template #default="scope">
              <el-select v-model="scope.row.type" placeholder="请选择商品种类">
                <el-option
                  v-for="dict in sys_goods_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </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>
  </div>
</template>

<script setup>
import { listCustomer, getCustomer, delCustomer, addCustomer, updateCustomer } from "@/api/demo/customer";
const { proxy } = getCurrentInstance();
const {sys_goods_type, sys_user_sex } = proxy.useDict('sys_goods_type', 'sys_user_sex');

// 遮罩层
const loading = ref(true);
// 选中数组
const ids = ref([]);
// 子表选中数据
const checkedDemoGoods= ref([])
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 总条数
const total = ref(0);
// 是否显示弹出层
const open = ref(false);
// 弹出层标题
const title = ref("");
// 显示搜索条件
const showSearch = ref(true);
// 客户主表(mb)表格数据
const customerList = ref([]);
// 商品子表格数据
const demoGoodsList = ref([]);

const data = reactive({
  // 表单参数
  form: {},
  // 查询参数
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    customerName: undefined,
    phonenumber: undefined,
    sex: undefined,
    birthday: undefined
  },
  // 表单校验
  rules: {
    customerName: [{ required: true, message: "客户姓名不能为空", trigger: "blur" }],
    phonenumber: [{required: true, message: "手机号码不能为空", trigger: "blur" }],
    sex: [{ required: true, message: "性别不能为空", trigger: "change" }],
    birthday: [{ required: true, message: "生日不能为空", trigger: "blur" }]
  }
});

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

/** 查询客户主表(mb)列表 */
function getList() {
  loading.value = true;
  listCustomer(queryParams.value).then(response => {
    customerList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
// 取消按钮
function cancel() {
  open.value = false;
  reset();
}
// 表单重置
function reset() {
  form.value = {
    customerId: undefined,
    customerName: undefined,
    phonenumber: undefined,
    sex: undefined,
    birthday: undefined,
    remark: undefined
  };
  demoGoodsList.value = [];
  proxy.resetForm("customerRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryFormRef");
  handleQuery();
}
// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.customerId)
  single.value = selection.length!==1
  multiple.value = !selection.length
}
/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加客户主表(mb)";
}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const customerId = row.customerId || ids.value
  getCustomer(customerId).then(response => {
    form.value = response.data;
    demoGoodsList.value = response.data.demoGoodsList;
    open.value = true;
    title.value = "修改客户主表(mb)";
  });
}
/** 删除按钮操作 */
function handleDelete(row) {
  const customerIds = row.customerId || ids.value;
  proxy.$modal.confirm('是否确认删除客户主表(mb)编号为"' + customerIds + '"的数据项？').then(function() {
    return delCustomer(customerIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["customerRef"].validate(valid => {
    if (valid) {
      form.value.demoGoodsList = demoGoodsList;
      if (form.value.customerId != null) {
        updateCustomer(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addCustomer(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
/** 商品子序号 */
function rowDemoGoodsIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}
/** 商品子添加按钮操作 */
function handleAddDemoGoods() {
  let obj = {};
  obj.name = "";
  obj.weight = 1;
  obj.price = 0.0;
  obj.date = "";
  obj.type = "";
  demoGoodsList.value.push(obj);
}
/** 商品子删除按钮操作 */
function handleDeleteDemoGoods() {
  if (checkedDemoGoods.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的商品子数据");
  } else {
    const goodsList = demoGoodsList.value;
    const checkedGoods = checkedDemoGoods.value;
    demoGoodsList.value = goodsList.filter(function(item) {
      return checkedGoods.indexOf(item.index) == -1
    });
  }
}
/** 复选框选中数据 */
function handleDemoGoodsSelectionChange(selection) {
  checkedDemoGoods.value = selection.map(item => item.index)
}
/** 导出按钮操作 */
function handleExport() {
  proxy.download('demo/customer/export', {
    ...queryParams.value
  }, `customer_${new Date().getTime()}.xlsx`)
}

getList();

</script>
