<script lang="ts" setup name="ListSourceAdd">
import { ref } from 'vue'
import type { Ref } from 'vue'
import { ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { useRoute } from 'vue-router'
import type { optionsType, priceForm } from './list_interface'
import { getPriceAddList, getQueryPriceInfo, getTypeSelect, getUpdatePriceInfo } from '@/api/system/price'

const loading = ref(false) // 表单加载状态
const infoId = ref('') // id
const pageType = ref('add') // 页面类型: add,edit, detail
const buttonLoading = ref(false) // 按钮加载状态
const textMap: { [key: string]: string } = {
  edit: '编辑',
  add: '新建',
  detail: '详情',
}// 字典
// 从路由中获取页面类型参数
const $route = useRoute()
if ($route.params && $route.params.type) {
  pageType.value = $route.params.type as string
  if ($route.params.id) {
    infoId.value = $route.params.id as string
  }
}
const defaultForm: priceForm = {
  checkType: '',
  createTime: null,
  directorDiscountPermission: '',
  id: null,
  isDel: 0,
  model: '',
  operatorDiscountPermission: '',
  price: '',
  priceDescription: '',
  priceItem: '',
  priceLimit: '',
  priceName: '',
  priceNo: '',
  priceStandard: '',
  priceType: '',
  remark: '',
  updateTime: null,
}
const formInline: Ref<priceForm> = ref({ ...defaultForm })
const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules>({
  priceName: [{ required: true, message: '价格名称不能为空', trigger: 'blur' }],
  checkType: [{ required: true, message: '校验类型不能为空', trigger: 'blur' }],
  priceType: [{ required: true, message: '类别不能为空', trigger: 'blur' }],
  priceItem: [{ required: true, message: '项目不能为空', trigger: 'blur' }],
  priceStandard: [{ required: true, message: '依据标准不能为空', trigger: 'blur' }],
  price: [{ required: true, message: '标准价格不能为空', trigger: 'blur' }],
  operatorDiscountPermission: [{ required: true, message: '业务员折扣权限不能为空', trigger: 'blur' }],
  directorDiscountPermission: [{ required: true, message: '负责人折扣权限不能为空', trigger: 'blur' }],
}) // 表单验证规则
const checkTypeOptions = ref<optionsType[]>([])
const priceTypeOptions = ref<optionsType[]>([])
const priceItemOptions = ref<optionsType[]>([])
const operatorDiscountPermissionOptions = ref<optionsType[]>([])
const directorDiscountPermissionOptions = ref<optionsType[]>([])
const $router = useRouter()
const close = () => {
  $router.back()
}
// 获取detail信息
const getInfo = () => {
  loading.value = true
  getQueryPriceInfo({ id: infoId.value }).then((res) => {
    formInline.value = res.data
    loading.value = false
  })
}
// 获取下拉框数据
const getOptions = (code: string) => {
  getTypeSelect(code).then((res) => {
    if (code === 'checkType') {
      checkTypeOptions.value = res.data
    }
    else if (code === 'priceType') {
      priceTypeOptions.value = res.data
    }
    else if (code === 'priceItem') {
      priceItemOptions.value = res.data
    }
    else if (code === 'operatorDiscountPermission') {
      operatorDiscountPermissionOptions.value = res.data
    }
    else if (code === 'directorDiscountPermission') {
      directorDiscountPermissionOptions.value = res.data
    }
  })
}
getOptions('checkType')
getOptions('priceType')
getOptions('priceItem')
getOptions('operatorDiscountPermission')
getOptions('directorDiscountPermission')

const printObj = ref({
  id: 'form', // 需要打印元素的id
  popTitle: '价格列表详情', // 打印配置页上方的标题
  extraHead: '<div style="display: flex;flex-direction: column;text-align: center"><h3>价格列表详情</h3></div>', // 最上方的头部文字，附加在head标签上的额外标签，使用逗号分割
  preview: false, // 是否启动预览模式，默认是false
  standard: '',
  extarCss: '',
})

// 点击提交/导出按钮
const getAddList = async (formEl: FormInstance | undefined, type: string) => {
  if (!formEl) { return }
  await formEl.validate((valid, fields) => {
    if (valid) {
      ElMessageBox.confirm(
    `确认${type}吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
      ).then(() => {
      // 新增提交
        if (type === '提交' && pageType.value !== 'edit') {
          buttonLoading.value = true
          getPriceAddList(formInline.value).then((res) => {
            if (res.code === 200) {
              close()
            }
            buttonLoading.value = false
          }).catch(_ => buttonLoading.value = false)
        }
        // 编辑提交
        else if (type === '提交' && pageType.value === 'edit') {
          formInline.value.id = infoId.value
          buttonLoading.value = true
          delete formInline.value.isDel
          delete formInline.value.createTime
          delete formInline.value.historicalPriceList
          delete formInline.value.updateTime
          getUpdatePriceInfo(formInline.value).then((res) => {
            if (res.code === 200) {
              close()
            }
            buttonLoading.value = false
          }).catch(_ => buttonLoading.value = false)
        }
        else {
          // 打印

        }
      })
    }
  })
}
if (pageType.value !== 'add') {
  getInfo()
}
</script>

<template>
  <app-container>
    <detail-page :title="`价格列表-${textMap[pageType]}`">
      <template #btns>
        <el-button v-if="pageType !== 'detail'" type="primary" @click="getAddList(ruleFormRef, '提交')">
          提交
        </el-button>
        <el-button v-if="pageType === 'detail'" v-print="printObj" type="primary">
          打印
        </el-button>
        <el-button type="info" @click="close">
          关闭
        </el-button>
      </template>
      <div id="form">
        <el-form
          ref="ruleFormRef"
          v-loading="loading"
          :model="formInline"
          label-width="auto"
          class="demo-form-inline"
          label-position="right"
          :rules="rules"
        >
          <el-row :gutter="24" class="marg">
            <el-col :span="6">
              <el-form-item label="价格名称:" prop="priceName">
                <el-input
                  v-model.trim="formInline.priceName"
                  :placeholder="pageType === 'detail' ? '' : '价格名称'"
                  :disabled="pageType === 'detail'"
                  class="full-width-input"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="检校类型:" prop="checkType">
                <el-select
                  v-model.trim="formInline.checkType"
                  clearable
                  :placeholder="pageType === 'detail' ? '' : '请选择检校类型'"
                  :disabled="pageType === 'detail'"
                  class="full-width-input"
                >
                  <el-option
                    v-for="item in checkTypeOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="类别:" prop="priceType">
                <el-select
                  v-model.trim="formInline.priceType"
                  clearable
                  :placeholder="pageType === 'detail' ? '' : '请选择类别'"
                  :disabled="pageType === 'detail'"
                  class="full-width-input"
                >
                  <el-option
                    v-for="item in priceTypeOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="项目:" prop="priceItem">
                <el-select
                  v-model.trim="formInline.priceItem"
                  clearable
                  :placeholder="pageType === 'detail' ? '' : '请选择项目'"
                  :disabled="pageType === 'detail'"
                  class="full-width-input"
                >
                  <el-option
                    v-for="item in priceItemOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" class="marg">
            <el-col :span="6">
              <el-form-item label="依据标准:" prop="priceStandard">
                <el-input
                  v-model.trim="formInline.priceStandard"
                  clearable
                  :placeholder="pageType === 'detail' ? '' : '依据标准'"
                  :disabled="pageType === 'detail'"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="标准价格（元):" prop="price">
                <el-input
                  v-model.trim="formInline.price"
                  clearable
                  :placeholder="pageType === 'detail' ? '' : '标准价格（元)'"
                  :disabled="pageType === 'detail'"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="限制范围:">
                <el-input
                  v-model="formInline.priceLimit"
                  :placeholder="pageType === 'detail' ? '' : '限制范围'"
                  :disabled="pageType === 'detail'"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="说明:">
                <el-input v-model="formInline.priceDescription" :placeholder="pageType === 'detail' ? '' : '说明'" :disabled="pageType === 'detail'" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" class="marg">
            <el-col :span="12">
              <el-form-item label="业务员折扣权限:" prop="operatorDiscountPermission">
                <el-select
                  v-model.trim="formInline.operatorDiscountPermission"
                  clearable
                  :placeholder="pageType === 'detail' ? '' : '请选择业务员折扣权限'"
                  :disabled="pageType === 'detail'"
                  class="full-width-input"
                >
                  <el-option
                    v-for="item in operatorDiscountPermissionOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" class="marg">
            <el-col :span="12">
              <el-form-item label="负责人折扣权限:" prop="directorDiscountPermission">
                <el-select
                  v-model.trim="formInline.directorDiscountPermission"
                  clearable
                  :placeholder="pageType === 'detail' ? '' : '请选择负责人折扣权限'"
                  :disabled="pageType === 'detail'"
                  class="full-width-input"
                >
                  <el-option
                    v-for="item in directorDiscountPermissionOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" class="marg">
            <el-col :span="12">
              <el-form-item label="备注:">
                <el-input v-model="formInline.remark" :placeholder="pageType === 'detail' ? '' : '备注'" :disabled="pageType === 'detail'" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </detail-page>
  </app-container>
</template>

<style lang="scss" scoped>
// 样式
</style>
