<template>
  <view class="page detail">
    <view class="form-content" style="height: 100%; overflow-y: auto">
      <uni-forms ref="formRef" :model-value="form" :rules="rules" err-show-type="toast" labelWidth="140px">
        <uni-section :title="$t('ledger.form.basicInfo')">
          <view class="card">
            <!-- 填写设备编码 -->
            <uni-forms-item class="form-item" name="deviceCode" :label="$t('ledger.form.deviceCode')" required>
              <uni-easyinput
                  v-model="form.deviceCode"
                  :inputBorder="false"
                  :clearable="false"
                  :styles="{disableColor:'#fff'}"
                  :placeholder="$t('operation.PleaseFillIn')"
                  style="text-align: right"
              />
            </uni-forms-item>

            <!-- 填写设备名称 -->
            <uni-forms-item class="form-item" name="deviceName" :label="$t('ledger.form.deviceName')" required>
              <uni-easyinput
                  v-model="form.deviceName"
                  :inputBorder="false"
                  :clearable="false"
                  :styles="{disableColor:'#fff'}"
                  :placeholder="$t('operation.PleaseFillIn')"
                  style="text-align: right"
              />
            </uni-forms-item>

            <!-- 选择品牌 -->
            <uni-forms-item class="form-item" name="brandName" :label="$t('ledger.form.brand')" required>
              <uni-easyinput
                  class="input-readonly"
                  v-model="form.brandName"
                  :inputBorder="false"
                  :clearable="false"
                  :styles="{disableColor:'#fff'}"
                  :placeholder="$t('operation.PleaseSelect')"
                  style="text-align: right"
                  @click.passive="selectBrand"
              />
            </uni-forms-item>

            <!-- 选择所在部门 -->
            <uni-forms-item class="form-item dept" name="deptList" :label="$t('ledger.form.dept')" required>
              <customthree-tree-select
                  v-model="form.deptList"
                  :list-data="deptTree"
                  @select-change="onSelectDept"
              />
            </uni-forms-item>

            <!-- 选择设备类别 -->
            <uni-forms-item class="form-item dept" name="deviceTypeList" :label="$t('ledger.form.deviceType')" required>
              <customthree-tree-select
                  v-model="form.deviceTypeList"
                  :list-data="deviceTypeTree"
                  @select-change="onSelectDeviceType"
              />
            </uni-forms-item>

            <!-- 选择设备状态 -->
            <uni-forms-item class="form-item" name="deviceStatus" :label="$t('ledger.form.deviceStatus')" required>
              <uni-data-picker
                  class="hidden"
                  v-model="form.deviceStatus"
                  :popup-title="$t('ledger.form.deviceStatus')"
                  :localdata="statusList"
                  :clear-icon="false"
                  :map="{ text: 'label', value: 'value' }"
              />
            </uni-forms-item>

            <!-- 选择资产性质 -->
            <uni-forms-item class="form-item" name="assetProperty" :label="$t('ledger.form.assetProperty')" required>
              <uni-data-select
                  :localdata="assetPropertyList"
                  field="value as value, label as text, label as label"
                  format="{label}"
                  :label="$t('operation.PleaseSelect')"
                  v-model="form.assetProperty"
                  :clear="false"
              />
            </uni-forms-item>

            <!-- 选择规格型号 -->
            <uni-forms-item class="form-item" name="modelName" :label="$t('ledger.form.model')">
              <uni-easyinput
                  class="input-readonly"
                  v-model="form.modelName"
                  :inputBorder="false"
                  :clearable="false"
                  :styles="{disableColor:'#fff'}"
                  :placeholder="$t('operation.PleaseSelect')"
                  style="text-align: right"
                  @click.passive="selectModel"
              />
            </uni-forms-item>

            <!-- 上传图片 -->
            <uni-forms-item class="form-item image" name="imageList" :label="$t('ledger.form.image')" style="padding-top: 25px; padding-bottom: 25px">
              <uni-file-picker
                v-model="form.imageList"
                file-mediatype="image"
                mode="grid"
                :auto-upload="false"
                :limit="1"
                @select="upload"
              >
                <template #default>
                  <view class="flex-col align-center justify-center" style="width: 60px; height: 60px; background-color: #F4F4F4">
                    <uni-icons type="plusempty" color="#ACACAC" size="12" />
                  </view>
                </template>
              </uni-file-picker>
            </uni-forms-item>

            <!-- 填写备注 -->
            <uni-forms-item class="form-item no-border" name="infoRemark" :label="$t('ledger.form.remark')">
              <uni-easyinput
                  v-model="form.infoRemark"
                  :inputBorder="false"
                  :clearable="false"
                  :styles="{disableColor:'#fff'}"
                  :placeholder="$t('operation.PleaseFillIn')"
                  style="text-align: right"
              />
            </uni-forms-item>
          </view>
        </uni-section>
        <uni-section :title="$t('ledger.form.produceInfo')">
          <view class="card">
            <!-- 选择制造商 -->
            <uni-forms-item class="form-item" name="zzName" :label="$t('ledger.form.manufacturer')" required>
              <uni-easyinput
                class="input-readonly"
                v-model="form.zzName"
                :inputBorder="false"
                :clearable="false"
                :styles="{disableColor:'#fff'}"
                :placeholder="$t('operation.PleaseSelect')"
                style="text-align: right"
                @click.passive="selectManufacturer(1)"
              />
            </uni-forms-item>

            <!-- 选择生产日期-->
            <uni-forms-item class="form-item" name="manDate" :label="$t('ledger.form.manDate')" required>
              <uni-datetime-picker
                  v-model="form.manDate"
                  type="date"
                  return-type="string"
                  :placeholder="$t('operation.PleaseSelect')"
                  :class="!form.manDate ? 'time-hint-color' : undefined"
                  :border="false"
              />
            </uni-forms-item>

            <!-- 选择供应商 -->
            <uni-forms-item class="form-item" name="supplierName" :label="$t('ledger.form.supplier')">
              <uni-easyinput
                  class="input-readonly"
                  v-model="form.supplierName"
                  :inputBorder="false"
                  :clearable="false"
                  :styles="{disableColor:'#fff'}"
                  :placeholder="$t('operation.PleaseSelect')"
                  style="text-align: right"
                  @click.passive="selectManufacturer(2)"
              />
            </uni-forms-item>

            <!-- 选择质保到期 -->
            <uni-forms-item class="form-item" name="expires" :label="$t('ledger.form.expires')">
              <uni-datetime-picker
                  v-model="form.expires"
                  type="date"
                  return-type="string"
                  :placeholder="$t('operation.PleaseSelect')"
                  :class="!form.expires ? 'time-hint-color' : undefined"
                  :border="false"
              />
            </uni-forms-item>

            <!-- 填写铭牌信息 -->
            <uni-forms-item class="form-item no-border" name="nameplate" :label="$t('ledger.form.nameplate')">
              <uni-easyinput
                  v-model="form.nameplate"
                  :inputBorder="false"
                  :clearable="false"
                  :styles="{disableColor:'#fff'}"
                  :placeholder="$t('operation.PleaseFillIn')"
                  style="text-align: right"
              />
            </uni-forms-item>
          </view>
        </uni-section>
        <uni-section :title="$t('ledger.form.financeInfo')">
          <view class="card">
            <!-- 选择采购价格 -->
            <uni-forms-item class="form-item" name="plPrice" :label="$t('ledger.form.plPrice')">
              <uni-easyinput
                  v-model="form.plPrice"
                  type="number"
                  :inputBorder="false"
                  :clearable="false"
                  :styles="{disableColor:'#fff'}"
                  :placeholder="$t('operation.PleaseFillIn')"
                  style="text-align: right"
              />
            </uni-forms-item>

            <!-- 选择采购日期 -->
            <uni-forms-item class="form-item" name="plDate" :label="$t('ledger.form.plDate')">
              <uni-datetime-picker
                  v-model="form.plDate"
                  type="date"
                  return-type="string"
                  :placeholder="$t('operation.PleaseSelect')"
                  :class="!form.plDate ? 'time-hint-color' : undefined"
                  :border="false"
              />
            </uni-forms-item>

            <!-- 填写折旧年限 -->
            <uni-forms-item class="form-item" name="plYear" :label="$t('ledger.form.plYear')">
              <uni-easyinput
                  v-model="form.plYear"
                  type="number"
                  :inputBorder="false"
                  :clearable="false"
                  :styles="{disableColor:'#fff'}"
                  :placeholder="$t('operation.PleaseFillIn')"
                  style="text-align: right"
              />
            </uni-forms-item>

            <!-- 选择折旧开始日期 -->
            <uni-forms-item class="form-item" name="plStartDate" :label="$t('ledger.form.plStartDate')">
              <uni-datetime-picker
                  v-model="form.plStartDate"
                  type="date"
                  return-type="string"
                  :placeholder="$t('operation.PleaseSelect')"
                  :class="!form.plStartDate ? 'time-hint-color' : undefined"
                  :border="false"
              />
            </uni-forms-item>

            <!-- 填写已提折旧月数 -->
            <uni-forms-item class="form-item" name="plMonthed" :label="$t('ledger.form.plMonth')">
              <uni-easyinput
                  v-model="form.plMonthed"
                  type="number"
                  :inputBorder="false"
                  :clearable="false"
                  :styles="{disableColor:'#fff'}"
                  :placeholder="$t('operation.PleaseFillIn')"
                  style="text-align: right"
              />
            </uni-forms-item>

            <!-- 填写已提折旧金额 -->
            <uni-forms-item class="form-item" name="plAmounted" :label="$t('ledger.form.plAmounted')">
              <uni-easyinput
                  v-model="form.plAmounted"
                  type="number"
                  :inputBorder="false"
                  :clearable="false"
                  :styles="{disableColor:'#fff'}"
                  :placeholder="$t('operation.PleaseFillIn')"
                  style="text-align: right"
              />
            </uni-forms-item>

            <!-- 填写剩余金额 -->
            <uni-forms-item class="form-item no-border" name="remainAmount" :label="$t('ledger.form.remainAmount')">
              <uni-easyinput
                  v-model="form.remainAmount"
                  type="number"
                  :inputBorder="false"
                  :clearable="false"
                  :styles="{disableColor:'#fff'}"
                  :placeholder="$t('operation.PleaseFillIn')"
                  style="text-align: right"
              />
            </uni-forms-item>
          </view>
        </uni-section>
        <view style="height: 50px"/>
      </uni-forms>
    </view>
    <button class="submit-btn" type="primary" @click="submit">{{ $t('operation.save') }}</button>
    <supplier-choose
        ref="manufacturerPopup"
        :selected-item-id="zzType === 1 ? form.manufacturerId : form.supplierId"
        @confirm="onSelectedManufacturer"
    />
    <brand-choose ref="brandPopup" :selected-item-id="form.brand" @confirm="onSelectBrand" />
    <model-choose ref="modelPopup" :selected-item-id="form.model" :brand-id="form.brand" @confirm="onSelectModel" />
  </view>
</template>

<script setup>
import { reactive, ref, onMounted, nextTick, getCurrentInstance } from 'vue'
import { useDataDictStore } from "@/store/modules/dataDict"
import { getAllDeptList, getAllDeviceList, uploadFile } from "@/api"
import { useDeptStore } from "@/store/modules/dept";
import supplierChoose from '@/components/supplier/choose.vue'
import brandChoose from "@/components/device/brandChoose.vue";
import modelChoose from "@/components/device/modelChoose.vue";
import { useDeviceStore } from "@/store/modules/device";
import { submitDeviceLedger } from "@/api/ledger";

const { deviceTypeTree } = useDeviceStore()
const { deptTree } = useDeptStore()
const { getDataDictList } = useDataDictStore()
const statusList = ref([])

const formRef = ref()
const form = reactive({
  deviceCode: '',
  deviceName: '',
  brand: undefined,
  brandName: '',
  deptId: '',
  deptList: [],
  deviceStatus: '',
  deviceTypeList: [],
  assetClass: '',
  assetClassName: '',
  assetProperty: '',
  model: undefined,
  modelName: '',
  picUrl: '',
  imageList: [],
  infoRemark: '',
  manufacturerId: undefined,
  zzName: '',
  manDate: '',
  supplierId: undefined,
  supplierName: '',
  expires: '',
  nameplate: '',
  plPrice: '',
  plDate: '',
  plYear: '',
  plStartDate: '',
  plMonthed: '',
  plAmounted: '',
  remainAmount: '',
})

const { appContext } = getCurrentInstance()
const t = appContext.config.globalProperties.$t
const rules = reactive({
  deviceCode: { rules: [{ required: true, errorMessage: t('ledger.form.deviceCodeError') }] },
  deviceName: { rules: [{ required: true, errorMessage: t('ledger.form.deviceNameError') }] },
  brand: { rules: [{ required: true, errorMessage: t('ledger.form.brandError') }] },
  deptList: { rules: [{ required: true, errorMessage: t('ledger.form.deptError') }] },
  deviceTypeList: { rules: [{ required: true, errorMessage: t('ledger.form.deviceTypeError') }] },
  deviceStatus: { rules: [{ required: true, errorMessage: t('ledger.form.deviceStatusError') }] },
  assetProperty: { rules: [{ required: true, errorMessage: t('ledger.form.assetPropertyError') }] },
  zzName: { rules: [{ required: true, errorMessage: t('ledger.form.manufacturerError') }] },
  manDate: { rules: [{ required: true, errorMessage: t('ledger.form.manDateError') }] },
})

// 选择部门
const onSelectDept = (item) => {
  if (item) {
    const list = JSON.parse(JSON.stringify(item))
    form.deptId = Array.isArray(list) && list.length > 0 ? list[0].id : undefined
  } else {
    form.deptId = undefined
  }
}

// 选择设备类型
const onSelectDeviceType = (item) => {
  if (item) {
    const list = JSON.parse(JSON.stringify(item))
    if (Array.isArray(list) && list.length > 0) {
      form.assetClass = list[0].id
      form.assetClassName = list[0].name
    } else {
      form.assetClass = undefined
      form.assetClassName = undefined
    }
  } else {
    form.assetClass = undefined
    form.assetClassName = undefined
  }
}

// 品牌弹窗
const brandPopup = ref()
const selectBrand = () => {
  brandPopup.value.open('bottom')
}
const onSelectBrand = (item) => {
  form.brand = item.id
  form.brandName = item.label
}

// 规格弹窗
const modelPopup = ref()
const selectModel = () => {
  if (!form.brand) {
    uni.showToast({ title: t('ledger.brand.hint'), icon: 'none' })
    return
  }
  modelPopup.value.open('bottom')
}
const onSelectModel = (item) => {
  form.model = item.id
  form.modelName = item.name
}

// 制造商弹窗
const zzType = ref()
const manufacturerPopup = ref()
const selectManufacturer = (type) => {
  zzType.value = type
  manufacturerPopup.value.open('bottom')
}
const onSelectedManufacturer = (item) => {
  if (zzType.value === 1) {
    form.manufacturerId = item.id
    form.zzName = item.name
  } else {
    form.supplierId = item.id
    form.supplierName = item.name
  }
}

// 上传图片
const upload = async (event) => {
  for (const path of event.tempFilePaths) {
    form.picUrl = (await uploadFile(path)).data
  }
}

// 提交
const submit = async () => {
  try {
    await formRef.value.validate()

    const { deptList, deviceTypeList, imageList, ...data } = form
    await submitDeviceLedger(data)
    uni.showToast({ title: t('statusChange.form.success'), icon: 'none' })
    uni.navigateBack()
    uni.$emit('update')
  } catch (e) {
    console.log(e)
  }
}

const assetPropertyList = ref([])
const deviceList = ref([])
const filterList = ref([])
onMounted(async () => {
  assetPropertyList.value = getDataDictList('pms_asset_property') // 获取资产性质字典
  statusList.value = getDataDictList('pms_device_status') // 获取设备状态字典
  const deptList = (await getAllDeptList()).data
  for (const dept of deptList) {
    if (dept.name === '科瑞石油技术') {
      deviceList.value = (await getAllDeviceList(dept.id)).data
      filterList.value = deviceList.value
      break
    }
  }

  await nextTick(() => { // 输入框禁止输入
    const inputViews = document.getElementsByClassName('input-readonly');
    for (const view of inputViews) {
      view.readOnly = true
    }
  })
})
</script>

<style lang="scss" scoped>
@import "@/style/choose-device.scss";

:deep(.uni-section) {
  background-color: transparent;
}

:deep(.uni-forms-item) {
  border-bottom: 1px dashed #CACCCF;
  margin: 0 20px;
  font-size: 13px;
}

.no-border {
  border-bottom: none;
}

:deep(.uni-forms-item__label) {
  color: #333333;
  font-weight: 500;
  font-size: 16px;
}

:deep(.image .uni-forms-item__label) {
  width: fit-content !important;
}

:deep(.file-picker__box) {
  width: 60px !important;
  height: 60px !important;
  padding: 0;
}

:deep(.uni-easyinput__content-input) {
  padding: 0 !important;
}

:deep(.uni-easyinput__placeholder-class) {
  font-size: 13px;
}

:deep(.input-value-border) {
  border: 0 !important;
}

:deep(.input-value) {
  text-align: end;
  padding-right: 0;
}

:deep(.hidden .uni-data-tree-dialog .selected-list) {
  display: none;
}

:deep(.selected-area .hidden) {
  display: block;
  margin-right: 5px;
}

:deep(.selected-area) {
  justify-content: end;
  font-size: 13px;
}

:deep(.uni-select) {
  padding-right: 0;

  .uni-select__input-placeholder {
    font-size: 13px;
    color: #999999;
  }

  .uni-icons {
    display: none;
  }
}

:deep(.placeholder) {
  color: #999999;
}

:deep(.selected-list) {
  justify-content: end;
}

:deep(.uni-data-pickerview) {
  display: block;
}

:deep(.uni-data-pickerview .selected-area .hidden) {
  display: none;
}

:deep(.tab-c .hidden) {
  margin-left: 30px;
  margin-right: 30px;
  border-top: 1px dashed #CACCCF;

  .item {
    border-bottom: 1px dashed #CACCCF !important;
  }
}

:deep(.uni-date-x) {
  text-align: right;
  color: inherit;
  padding-right: 0;

  .icon-calendar {
    display: none;
    font-size: 0;
  }
  .uni-date__x-input {
    font-size: inherit;
    padding-right: 0;
  }
}

:deep(.uni-select) {
  border: none;
  font-size: 13px !important;
}

:deep(.uni-select__input-text) {
  text-align: end;
}

:deep(.dept) {
  .uni-forms-item__content {
    display: flex;
    align-items: center;
    justify-content: end;
  }
  .select-list {
    border: none;
    min-height: 0;
    padding: 0;
    border-radius: 0;
  }

  .no-data {
    text-align: end;
    font-size: 13px;
    color: #999999 !important;
  }

  .select-items {
    justify-content: end;
  }

  .select-item {
    padding-right: 0 !important;
    margin: 0 !important;
    background-color: transparent !important;
  }

  .name {
    padding-right: 0 !important;
  }

  .close {
    display: none !important;
  }
}

:deep(.select-list .right) {
  display: none !important;
}

:deep(.arrow-area) {
  display: none;
}

.popup-content {
  height: 500px;
}

.device-item {
  height: 35px;
  line-height: 35px;
  padding: 0 30px;
  font-size: 13px;
  color: #333333;
  border-bottom: 1px #CACCCF;
}

.selected {
  color: #004098;
}

.divider {
  height: 0.5px;
  margin: 0 28px;
  background-color: #CACCCF;
}

.z-page-popup {
  padding: 0;
  background: white;
  border-radius: 10px 10px 0 0;
}

.submit-btn {
  width: 100%;
  height: 48px;
  border-radius: 0;
  position: fixed;
  bottom: 0;
  left: 0;
}

.card {
  background-color: white;
}

.time-hint-color {
  color: #999999;
}

.input-readonly {
  caret-color: transparent;
}
</style>