<template>
  <el-dialog :title="props.title" v-model="isShowDetail" width="1120px" :before-close="closed">
    <div class="config">
      <el-form ref="ruleFormRef" label-width="180px" :model="info" label-suffix="：" :rules="rules"
        :disabled="props.title.includes('详情')" label-position="right">
        <el-row>
          <el-col :span="11">
            <el-form-item label="公司名称">
              <el-input v-model="info.orgName" disabled style="width: 350px;" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="统计年度">
              <el-input v-if="!isAdd" v-model="info.reportingYear" disabled style="width: 350px;" />
              <el-select v-else v-model="info.reportingYear" placeholder="请选择统计年度" style="width: 350px;" disabled>
                <el-option v-for="item in filterYear(7)" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="上报季度">
              <MOSTY.DictRidioAndSelect :dictData="D_BZ_QUARTER" v-model="info.reportCycleCode" style="width: 350px;"
                selectType="select" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="车牌号码" prop="cdCarNo">
              <!-- :disabled="!isAdd" -->
              <el-input v-model="info.cdCarNo" style="width: 100%;" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="资产权属" prop="cdMotorCarAssetOwnershipCode">
              <MOSTY.DictRidioAndSelect :dictData="D_BZ_CKQSLX" v-model="info.cdMotorCarAssetOwnershipCode"
                style="width: 350px;" selectType="select" @onChange="assetOwnerChange" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="车辆类型" prop="cdMotorCarTypeCode">
              <MOSTY.DictTree :zdbh="'D_TB_CLLX'" @onChange="changeCarTypeCode" @nameChange="carTypeNameChange"
                :placeholder="info.cdMotorCarTypeCode ? info.cdMotorCarTypeCode : '请选择车辆类型'" style="width: 350px;"
                clearable filterable v-model="cdMotorCarTypeCodeTemp" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="车辆用途类型" prop="cdMotorCarUsageCode">
              <el-input v-if="!['1', '2'].includes(info.cdMotorCarTypeCode && info.cdMotorCarTypeCode.charAt(0) || '')"
                placeholder="请先选车辆类型" readonly></el-input>
              <el-select v-model="info.cdMotorCarUsageCode" placeholder="请选择载货类型" style="width: 350px"
                v-if="info.cdMotorCarTypeCode && info.cdMotorCarTypeCode.charAt(0) == '2'">
                <el-option v-for="item in D_BZ_CLYT_ZK" :key="item.value" :label="item.label"
                  :value="item.value"></el-option>
              </el-select>
              <el-select v-model="info.cdMotorCarUsageCode" placeholder="请选择载客类型" style="width: 350px"
                v-if="info.cdMotorCarTypeCode && info.cdMotorCarTypeCode.charAt(0) == '1'">
                <el-option v-for="item in D_BZ_CLYT_ZH" :key="item.value" :label="item.label"
                  :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="机动车辆新能源车标识" prop="cdMotorCarNewEnergyCarFlag">
              <el-select v-model="info.cdMotorCarNewEnergyCarFlag" style="width: 350px;">
                <el-option label="是" :value="1" />
                <el-option label="否" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="车辆使用状态" prop="cdMotorCarUseStateCode">
              <el-select v-model="info.cdMotorCarUseStateCode" style="width: 350px;">
                <el-option label="在用" value="1" />
                <el-option label="已报废" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="车辆安全智能化" prop="cdCarSafeIntelligentCode">
              <!-- <MOSTY.DictRidioAndSelect :dictData="D_BZ_CLAQZNH" v-model="info.cdCarSafeIntelligentCode"
                selectType="select" style="width: 350px;" :multiple="true" /> -->
              <MOSTY.DictRidioAndSelect :dictData="D_BZ_CLAQZNH" v-model="info.cdCarSafeIntelligentCode"
                selectType="select" style="width: 1090px;" @getselect='onChangezrlx'
                :disabledItem="info.cdCarSafeIntelligentCode == '07' || info.cdCarSafeIntelligentCode == '' ? [] : ['07']"
                :multiple="true" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="采购时间" prop="cdMotorCarProcurementDate">
              <el-date-picker v-model="info.cdMotorCarProcurementDate" style="width: 350px" type="date"
                format="YYYY-MM-DD" value-format="YYYY-MM-DD" placeholder="请选择采购时间" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="行驶里程" prop="cdMotorCarMileageTraveled">
              <el-input v-model="info.cdMotorCarMileageTraveled" type='number' clearable style="width: 350px">
                <template #append>万公里</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="onSave" v-if="!props.title.includes('详情')" style="margin-right: 10px">
          <el-icon>
            <DocumentChecked />
          </el-icon>
          <span>保存</span></el-button>
        <el-button @click="closed"> <el-icon>
            <DocumentDelete />
          </el-icon>
          <span>关闭</span></el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance, computed } from "vue";
import { getApi, postApi } from "@/api/tobAcco_api.js";
import * as MOSTY from "@/components/MyComponents/index";
import { ElMessage } from "element-plus";
import * as rule from "@/utils/rules.js";
import { filterYear } from "@/utils/auth.js"
const { proxy } = getCurrentInstance();
const { D_BZ_CKQSLX, D_BZ_CLYT_ZH, D_BZ_CLYT_ZK, D_BZ_CLAQZNH, D_TB_CLLX, D_BZ_QUARTER } = proxy.$dict("D_TB_CLLX", "D_BZ_CKQSLX", "D_BZ_CLYT_ZH", "D_BZ_CLYT_ZK", "D_BZ_CLAQZNH", "D_BZ_QUARTER");

const props = defineProps({
  title: {
    type: String,
    default: ""
  },
  detail: {
    type: Object,
    default: () => { }
  },
  type: {
    type: String,
    default: ""
  },
  rowItem: {
    type: Object,
    default: () => { }
  }
});
const emit = defineEmits(["close"]);
const isShowDetail = ref(true);
const ruleFormRef = ref();
const cdMotorCarTypeCodeTemp = ref()
/** 是否是新增 */
const isAdd = computed(() => {
  return props.title.includes('新增')
})
const rules = reactive({
  'cdMotorCarAssetOwnershipCode': [{ required: true, message: '资产权属', trigger: 'blur' }],
  'cdMotorCarTypeCode': [{ required: true, message: '车辆类型', trigger: 'blur' }],
  'cdMotorCarUsageCode': [{ required: true, message: '车辆用途', trigger: 'blur' }],
  'cdMotorCarUseStateCode': [{ required: true, message: '车辆使用状态', trigger: 'blur' }],
  'cdMotorCarNewEnergyCarFlag': [{ required: true, message: '机动车辆新能源车标识', trigger: 'blur' }],
  'cdCarSafeIntelligentCode': [{ required: true, message: '车辆安全智能化代码', trigger: 'blur' }],
  'cdMotorCarProcurementDate': [{ required: true, message: '采购时间', trigger: 'blur' }],
  ...rule.numbernineRule({ validator: true, require: true, iszs: true, firstNum: 4, lastNum: 4 }, "cdMotorCarMileageTraveled"),
  'cdCarNo': [{ required: true, message: '车牌号码', trigger: 'blur' }],
});
const info = ref({});
/** 获取车辆用途名称 */
const getCarUsageName = () => {
  if (!info.value.cdMotorCarUsageCode) return
  let arr = []
  if (info.value.cdMotorCarTypeCode.charAt(0) == '1') arr = D_BZ_CLYT_ZH.value
  if (info.value.cdMotorCarTypeCode.charAt(0) == '2') arr = D_BZ_CLYT_ZK.value
  return arr.find(v => v.value == info.value.cdMotorCarUsageCode).label || ''
}


const onSave = async () => {
  await ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      let _arr = []
      if (Array.isArray(info.value.cdCarSafeIntelligentCode) && info.value.cdCarSafeIntelligentCode.length) {
        info.value.cdCarSafeIntelligentCode.map(item => {
          _arr.push(D_BZ_CLAQZNH.value.find(v => v.value == item).label)
        })
        info.value.cdCarSafeIntelligentName = _arr.join("、")
        info.value.cdCarSafeIntelligentCode = info.value.cdCarSafeIntelligentCode.join("、")
      }
      // info.cdMotorCarUsageCode
      const cdMotorCarUseStateCode = info.value.cdMotorCarUseStateCode
      let cdMotorCarUsageName = getCarUsageName()
      const params = {
        ...info.value,
        cdMotorCarUsageName: cdMotorCarUsageName,
        cdMotorCarUseStateName: { 1: '在用', 2: '已报废' }[cdMotorCarUseStateCode] || ''
      }

      const url = isAdd.value ? '/mosty-jcgl/data/Car/saveCar' : '/mosty-jcgl/data/Car/editCar'
      postApi(params, url).then(() => {
        ElMessage.success("保存成功");
        emit("close", true);
      }).finally(() => {
        info.value.cdCarSafeIntelligentCode = info.value.cdCarSafeIntelligentCode ? info.value.cdCarSafeIntelligentCode.split("、") : null
      })
    }
  });
};
/** 获取most tree回显的数据()
 * @param {String} val
 */
const getTreeNeedVal = (val) => {
  if (typeof val !== 'string') return
  if (!val) return
  let arr = val.split(',')
  return arr[arr.length - 1]
};
onMounted(() => {
  if (isAdd.value) {
    info.value = {
      orgCode: props.rowItem.orgCode && props.rowItem.orgCode.replace('XN', ''),
      orgName: props.rowItem.orgName,
      statId: props.rowItem.id,
      reportCycleCode: String(props.rowItem.reportCycleCode || ''),
      reportingYear: props.rowItem.reportingYear, // 默认当年
    }
  } else if (props.type == 'report') {
    info.value = props.detail
    info.value.cdCarSafeIntelligentCode = props.detail.cdCarSafeIntelligentCode.split("、")
    cdMotorCarTypeCodeTemp.value = getTreeNeedVal(info.value.cdMotorCarTypeCode)
  } else {
    getApi({}, `/mosty-jcgl/data/Car/selectOne/${props.detail.sourceId}`).then((res) => {
      info.value = res;
      info.value.reportCycleCode = String(info.value.reportCycleCode || '')
      info.value.cdCarSafeIntelligentCode = info.value.cdCarSafeIntelligentCode.split("、")

      cdMotorCarTypeCodeTemp.value = getTreeNeedVal(info.value.cdMotorCarTypeCode)
    });
  }
});
const assetOwnerChange = (val, label) => {
  info.value.cdMotorCarOwnershipName = label
}

const changeCarTypeCode = (val, valPath) => {
  info.value.cdMotorCarTypeCode = valPath.join(',')
  // 类型改变 清空用途
  info.value.cdMotorCarUsageCode = ''
}
const carTypeNameChange = (val, NamePath) => {
  console.log(NamePath, 'NamePath');

  info.value.cdMotorCarTypeName = NamePath?.length ? NamePath.join('-') : ''
}
function onChangezrlx(val) {
  if (val.value == '07') {

  }
  const index = info.value.cdCarSafeIntelligentCode.indexOf('07');
  if (info.value.cdCarSafeIntelligentCode.length > 1 && index !== -1) {
    info.value.cdCarSafeIntelligentCode.splice(index, 1)
  }

}
const closed = () => {
  if(!ruleFormRef.value) return
  if (!props.title.includes('详情')) {
    proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
      .then(() => {
        emit("close");
      })
      .catch(() => {
        // catch error
      })
  } else {
    emit("close");
  }

};
</script>
<style scoped lang="scss">
::v-deep .el-dialog__body {
  height: 100% !important;
}

.config {
  height: 55vh;
}

::v-deep .el-form-item--default {
  margin-left: 10px;
}
</style>
