<template>
  <super-dialog
    v-model="isShowDialog"
    :modal="false"
    :title="'路产赔偿清单'"
    :top="top"
    :width="width"
    v-bind="$attrs"
    @closed="closed"
    @open="open"
  >
    <div :style="{height}" class="eventInfo-dialog">
      <div class="form-module">
        <el-form
          ref="eventInfo"
          :model="eventInfo"
          :rules="rescueInfoRules"
          label-position="top"
          label-suffix="："
          label-width="100px"
        >
          <el-row :gutter="24">
            <el-col :span="6">
              <el-form-item label="赔偿分类" prop="propertySubjectType">
                <el-select
                  v-model="eventInfo.propertySubjectType"
                  clearable
                  disabled
                  placeholder="赔偿分类"
                  style="width: 100%"
                >
                  <el-option
                    v-for="(item, index) in getDictionaryByCode('lsxmpcfl')"
                    :key="index"
                    :label="item.name"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col v-if="eventInfo.propertySubjectType === '1'" :span="6">
              <el-form-item label="项目明细" prop="propertySubjectName">
                <el-input
                  v-model="eventInfo.propertySubjectName"
                  class="el-click-input"
                  clearable
                  placeholder="点击选择项目明细"
                  readonly
                  suffix-icon="el-icon-search"
                  @click.native="showDialog('roadDamageItem')"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="规格" prop="modle">
                <el-input
                  v-model="eventInfo.modle"
                  placeholder="请输入规格"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item :rules="[
                  { required: eventInfo.propertySubjectType === '1', message: '计费单位不能为空', trigger: 'blur' },
                ]" label="计费单位" prop="unit">
                <el-input
                  v-model="eventInfo.unit"
                  placeholder="请输入计费单位"
                >
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="6">
              <el-form-item :rules="[
                  { required: eventInfo.propertySubjectType === '1', message: '数量不能为空', trigger: 'blur' },
                ]" label="数量" prop="num">
                <el-input
                  v-model="eventInfo.num"
                  placeholder="请输入数量"
                  type="number"
                  @change="totalCount"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="9">
              <el-form-item
                :label="priceType === 'only' ? '收费单价' : priceTip"
                prop="price"
              >
                <el-input
                  v-model.number="eventInfo.price"
                  :placeholder="
                    priceType === 'only'
                      ? '请输入收费单价'
                      : '请根据收费单价范围输入单价'
                  "
                  type="number"
                  @change="totalCount"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="9">
              <el-form-item label="金额" prop="totle">
                <el-input
                  v-model="eventInfo.totle"
                  placeholder="根据单价和数量计算"
                >
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="备注" prop="memo">
                <el-input
                  v-model="eventInfo.memo"
                  :autosize="{minRows: 2, maxRows: 4}"
                  placeholder="请输入"
                  type="textarea"
                >
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div class="content-bottom">
          <el-button size="small" @click="isShowDialog = false">
            取 消
          </el-button>
          <el-button
            :disabled="tableLoading"
            size="small"
            type="primary"
            @click="handleAppoint"
          >
            确 定
          </el-button>
        </div>
      </div>
    </div>

    <RoadDamageItemDialog
      :fatherId="fatherId"
      :is-show.sync="roadDamageItemDialog"
      :roadId="roadId"
      :selected-content.sync="eventInfo.detail"
      @confirm="handleRoadDamageSelect"
    />
  </super-dialog>
</template>

<script>
import SuperDialog from '@/components/SuperDialog/index.vue'
import {getDictionaryByCode} from '@/utils/dictionary'
import RoadDamageItemDialog from './components/RoadDamageItemDialog'

export default {
  name: 'DetailedListGialog',
  inheritAttrs: false,
  //   mixins: [TableMixin],
  props: {
    isShow: {
      default: false,
      type: Boolean
    },
    selectedContent: {
      default: () => [],
      type: [Array, Object]
    },
    top: {
      default: '14vh',
      type: String
    },
    width: {
      default: '60%',
      type: String
    },
    height: {
      default: '65vh',
      type: String
    },
    confirmCloseDialog: {
      default: true,
      type: Boolean
    },
    roadId: {
      default: '',
      type: String
    },
    fatherId: {
      default: '',
      type: String
    },
    itemDetail: {
      default: () => {
      },
      type: Object
    }
  },
  components: {
    SuperDialog,
    RoadDamageItemDialog
  },
  data() {
    return {
      roadDamageItemDialog: false,
      initializeRendering: false, // 弹层内容初始化渲染
      tableMaxHeight: '600px',
      enhancedTableData: [], // 增强的表格数据（增加额外特性）
      eventInfo: {
        num: undefined
      },
      rescueInfoRules: {
        propertySubjectType: [
          {
            required: true,
            message: '请选择赔偿分类',
            trigger: ['change']
          }
        ],
        propertySubjectName: [
          {
            required: true,
            message: '请选择项目明细',
            trigger: ['change']
          }
        ],
        // modle: [
        //   {
        //     required: true,
        //     message: '规格不能为空',
        //     trigger: ['change']
        //   }
        // ],
        // num: [
        //   {
        //     required: true,
        //     message: '数量不能为空',
        //     trigger: ['change']
        //   }
        // ],
        // price: [
        //   {
        //     required: true,
        //     message: '单价不能为空',
        //     trigger: ['change']
        //   }
        // ],
        // unit: [
        //   {
        //     required: true,
        //     message: '计费单位不能为空',
        //     trigger: ['change']
        //   }
        // ],
        totle: [
          {
            required: true,
            message: '金额不能为空',
            trigger: ['change']
          }
        ],
        price: [
          {
            validator: (rule, value, callback) => {
              if (this.priceType === 'only') {
                if (value) {
                  callback()
                } else {
                  // callback(new Error('单价不能为空'))
                  callback()
                }
              } else {
                if (
                  value &&
                  value >= 0 &&
                  value <= this.eventInfo.maxPrice &&
                  value >= this.eventInfo.minPrice
                ) {
                  callback()
                } else {
                  callback(new Error('单价需在最小值和最大值之间，且不能为空'))
                }
              }
            }
          }
        ]
      },
      tableLoading: false,
      priceType: 'only', // 单价类型：only 单价；range 范围
      priceTip: ''
    }
  },
  computed: {
    isShowDialog: {
      get() {
        return this.isShow
      },
      set(val) {
        this.$emit('update:isShow', val)
      }
    }
  },
  methods: {
    getDictionaryByCode,
    // 打开弹层时触发
    open() {
      this.$nextTick(() => {
        let {
          propertySubjectName,
          propertySubjectId,
          propertySubjectType
        } = this.itemDetail
        this.eventInfo = this.itemDetail
        this.$set(
          this.eventInfo,
          'propertySubjectType',
          propertySubjectType || getDictionaryByCode('lsxmpcfl')[0].value
        )
        this.$set(this.eventInfo, 'detail', {
          propertySubjectName,
          propertySubjectId
        })
        console.log(this.itemDetail, '999999', this.eventInfo)
      })
    },
    totalCount() {
      if (this.eventInfo.num && this.eventInfo.price) {
        // let totle = this.eventInfo.num * this.eventInfo.price
        const factor = Math.pow(10, 4)
        let totle = Math.round(this.eventInfo.num * this.eventInfo.price * factor) / factor
        this.$set(this.eventInfo, 'totle', totle)
      }
    },
    // 展示弹层
    showDialog(dialogName) {
      if (!dialogName) return
      if (dialogName === 'userChoice') {
        if (!this.eventInfo.teamId) {
          this.$message.error('请先选择救援派遣队伍')
        } else {
          this[dialogName + 'Dialog'] = true
        }
      } else {
        this[dialogName + 'Dialog'] = true
      }
    },
    handleRoadDamageSelect(detail) {
      let {price, ...rest} = detail //   去掉已作废的price属性 防止与eventInfo冲突
      this.eventInfo = {...this.eventInfo, ...rest}
      this.eventInfo.propertyTypeId = detail.typeId
      this.$set(this.eventInfo, 'modle', detail.model)
      this.$set(this.eventInfo, 'totle', undefined)
      this.$set(this.eventInfo, 'num', undefined)
      if (detail.minPrice && detail.maxPrice) {
        if (detail.minPrice === detail.maxPrice) {
          this.priceType = 'only'
          this.$set(this.eventInfo, 'price', detail.minPrice)
        } else {
          this.priceType = 'range'
          this.priceTip =
            '收费单价 (范围：' +
            +detail.minPrice +
            ' 至 ' +
            detail.maxPrice +
            ')'
          this.$set(this.eventInfo, 'price', undefined)
        }
      } else {
        this.priceType = 'only'
        this.$set(this.eventInfo, 'price', detail.minPrice || detail.maxPrice)
      }
    },
    handleAppoint() {
      this.$refs.eventInfo.validate(async (valid, object) => {
        if (!valid) {
          this.$message.warning(
            `有${
              Object.keys(object).length
            }个字段未通过校验，请正确填写表单内容。`
          )
        } else {
          this.$confirm('确认保存路损赔偿清单信息吗？', '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async () => {
            try {
              this.$emit('sendData', this.eventInfo)
              this.closed()
            } finally {
            }
          })
        }
      })
    },
    // 关闭弹层触发
    closed() {
      const {orgData} = this
      // 重置data中的数据
      Object.assign(this.$data, this.$options.data.call(this), {orgData})
      this.$nextTick(() => {
        this.$refs.eventInfo?.clearValidate()
      })
      if (this.confirmCloseDialog) this.isShowDialog = false
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/assets/css/element-variables';

.el-icon-plus {
  cursor: pointer;
  display: block;
  height: 100%;
  font-size: 16px !important;
  font-weight: 900;
  color: #43a1ff;
}

.eventInfo-dialog {
  width: 100%;
  display: flex;
  flex-direction: column;
  column-gap: 16px;
  min-height: 50vh;

  .form-module {
    width: 100%;
    height: 100%;
    flex: 1;
    display: flex;
    flex-direction: column;
    row-gap: 16px;
    background-color: $--system-module-color1;
    padding: 16px;
    box-sizing: border-box;
    border-radius: 8px;

    .el-form {
      height: calc(100% - 40px);
      overflow-y: scroll;
    }

    .content-bottom {
      display: flex;
      justify-content: flex-end;
      height: 40px;
    }
  }
}

::v-deep::-webkit-scrollbar-thumb,
::v-deep::-webkit-scrollbar {
  display: none;
}
</style>
