<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="客户姓名" prop="customerName">
            <el-input v-model="queryParams.customerName" placeholder="请输入客户姓名" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="手机号码" prop="phonenumber">
            <el-input v-model="queryParams.phonenumber" placeholder="请输入手机号码" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="客户性别" prop="sex">
            <el-select v-model="queryParams.sex" placeholder="请选择客户性别" clearable style="width: 240px">
              <el-option
                v-for="dict in sys_user_gender"
                :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>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <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>
      </template>

      <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" v-if="false" />
        <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_gender" :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" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['demo:customer:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['demo:customer:remove']"></el-button>
            </el-tooltip>
          </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-card>
    <!-- 添加或修改客户主表对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="780px" append-to-body>
      <el-form ref="customerFormRef" :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_gender"
                :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"
            value-format="YYYY-MM-DD"
            placeholder="请选择客户生日">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="客户描述" prop="remark">
            <el-input v-model="form.remark" placeholder="请输入客户描述" />
        </el-form-item>
        <el-form-item label="乐观锁" prop="version" v-show="false">
            <el-input v-model="form.version" 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="handleAddGoods">添加</el-button>
          </el-col>
          <el-col :span="1.5">
              <el-button type="danger" icon="Delete" @click="handleDeleteGoods">删除</el-button>
          </el-col>
      </el-row>
      <el-table :data="goodsList" :row-class-name="rowGoodsIndex" @selection-change="handleGoodsSelectionChange" ref="goods">
          <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="请选择商品时间">
                      </el-date-picker>
                  </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-column v-if="false" label="乐观锁" prop="version" width="150">
                      <template #default="scope">
                          <el-input v-model="scope.row.version" placeholder="请输入乐观锁" />
                      </template>
                  </el-table-column>
      </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Customer" lang="ts">
import { listCustomer, getCustomer, delCustomer, addCustomer, updateCustomer } from '@/api/demo/customer';
import { DemoCustomerVO, DemoCustomerQuery, DemoCustomerForm, DemoGoodsVO } from '@/api/demo/customer/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_goods_type, sys_user_gender } = toRefs<any>(proxy?.useDict('sys_goods_type', 'sys_user_gender'));

// 表格数据
const customerList = ref<DemoCustomerVO[]>([]);
// 子表格数据
const goodsList = ref<DemoGoodsVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
// 选中数组
const ids = ref<Array<string | number>>([]);
// 子表选中数据
const checkedGoods = ref<DemoGoodsVO[]>([]);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 总条数
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const customerFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: DemoCustomerForm = {
  customerId: undefined,
  customerName: undefined,
  phonenumber: undefined,
  gender: undefined,
  birthday: undefined,
  remark: undefined,
  version: 0,
};
const data = reactive<PageData<DemoCustomerForm, DemoCustomerQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    customerName: undefined,
    phonenumber: undefined,
    sex: undefined,
    params: {
    }
  },
  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 { queryParams, form, rules } = toRefs(data);

/** 查询客户主表列表 */
const getList = async () => {
  loading.value = true;
  const res = await listCustomer(queryParams.value);
  customerList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  goodsList.value = [];
  customerFormRef.value?.resetFields();
};

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: DemoCustomerVO[]) => {
  ids.value = selection.map(item => item.customerId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加客户主表';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: DemoCustomerVO) => {
  reset();
  const _customerId = row?.customerId || ids.value[0];
  const res = await getCustomer(_customerId);
  Object.assign(form.value, res.data);
  goodsList.value = res.data.demoGoodsList;
  dialog.visible = true;
  dialog.title = '修改客户主表';
};

/** 提交按钮 */
const submitForm = () => {
  customerFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      form.value.goodsList = goodsList.value;
      if (form.value.customerId) {
        await updateCustomer(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addCustomer(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('修改成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: DemoCustomerVO) => {
  const _customerIds = row?.customerId || ids.value;
  await proxy?.$modal.confirm('是否确认删除客户主表编号为"' + _customerIds + '"的数据项？').finally(() => loading.value = false);
  await delCustomer(_customerIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
};

/** 商品子表序号 */
const rowGoodsIndex = ({row,rowIndex}: {row: DemoGoodsVO,rowIndex: number}) => {
    row.index = rowIndex + 1;
}

/** 商品子表添加按钮操作 */
const handleAddGoods = () => {
    let obj = {};
    obj.name = "";
    obj.weight = "";
    obj.price = "";
    obj.date = "";
    obj.type = "";
    obj.version = 0;
    goodsList.value.push(obj);
}

/** 商品子表删除按钮操作 */
const handleDeleteGoods = () => {
    if (checkedGoods.value.length == 0) {
        proxy.$modal.msgError("请先选择要删除的商品子表数据");
    } else {
        const goodss = goodsList.value;
        const checkedGoodss = checkedGoods.value;
        goodsList.value = goodss.filter(function(item) {
            return checkedGoodss.indexOf(item.index) == -1
        });
    }
}

/** 复选框选中数据 */
const handleGoodsSelectionChange = (selection: DemoGoodsVO[]) => {
    checkedGoods.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('demo/customer/export', {
    ...queryParams.value
  }, `customer_${new Date().getTime()}.xlsx`)
};

onMounted(() => {
  getList();
});
</script>
