<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="24">
           <a-form-model-item label="设备类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="deviceTypeId">
            <a-tree-select
              :disabled="model.id!=null"
              :trigger-change="true"
              v-model="model.deviceTypeId"
              :tree-data="deviceTypes"
              placeholder="请选择设备类型"
            />
          </a-form-model-item>
        </a-col>
          <a-col :span="24">
            <a-form-model-item label="部件类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="departTypeId">
              <a-tree-select
                :trigger-change="true"
                v-model="model.departTypeId"
                :tree-data="devicePartTypes"
                placeholder="请选择部件类型"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="故障类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="breakdownType">
              <j-dict-select-tag :disabled="model.id!=null" type="list" v-model="model.breakdownType" dictCode="breakdown_type" placeholder="请选择故障类型" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="故障编码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="breakCode">
              <a-input :disabled="model.id!=null" v-model="model.breakCode" placeholder="请输入故障编码" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="故障表现与影响" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="description">
              <a-textarea v-model="model.description" rows="4" placeholder="请输入故障表现与影响" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="故障原因" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="reason">
              <a-textarea v-model="model.reason" rows="4" placeholder="请输入故障原因" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="解决方法" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="solve">
              <a-textarea v-model="model.solve" rows="4" placeholder="请输入解决方法" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="材料1" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="instruction1">
              <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="uploadManualUrl" @change="info => handleUpload(info, 'instruction1')">
                <a-button icon="cloud-upload" >上传</a-button>
              </a-upload>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="材料2" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="instruction2">
              <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="uploadManualUrl" @change="info => handleUpload(info, 'instruction1')">
                <a-button icon="cloud-upload" >上传</a-button>
              </a-upload>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="材料3" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="instruction3">
              <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="uploadManualUrl" @change="info => handleUpload(info, 'instruction1')">
                <a-button icon="cloud-upload" >上传</a-button>
              </a-upload>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>

import { httpAction, getAction } from '@/api/manage'
import { ACCESS_TOKEN, TENANT_ID } from '@/store/mutation-types'
import Vue from 'vue'

export default {
  name: 'DeviceBreakdownDossierForm',
  components: {
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data () {
    return {
      model:{
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      confirmLoading: false,
      validatorRules: {
        deviceTypeId: [
          { required: true, message: '请输入设备类型!'},
        ],
        // departTypeId: [
        //   { required: true, message: '请输入部件类型!'},
        // ],
        breakdownType: [
          { required: true, message: '请输入故障类型!'},
        ],
        description: [
          { required: true, message: '请输入故障表现与影响!'},
        ],
      },
      deviceTypes: [],
      devicePartTypes: [],
      url: {
        add: "/device/deviceBreakdownDossier/add",
        edit: "/device/deviceBreakdownDossier/edit",
        uploadManual: "sys/upload/uploadMinioNew",
        listAllDeviceType:"/device/buDeviceType/list/all",
        listDeviceType:"/device/buDeviceType/list/deviceType",
        queryById: "/device/deviceBreakdownDossier/queryById"
      }
    }
  },
  watch: {
    'model.deviceTypeId': {
      handler(newVal,oldVal) {
        if(newVal != null && newVal != undefined) {
          this.loadDevicePartType();
        }
      }
    }
  },
  computed: {
    formDisabled(){
      return this.disabled
    },
    uploadManualUrl: function(){
      return `${window._CONFIG['domianURL']}/${this.url.uploadManual}`;
    },
    //token header
    tokenHeader(){
      let head = {'X-Access-Token': Vue.ls.get(ACCESS_TOKEN)}
      let tenantid = Vue.ls.get(TENANT_ID)
      if(tenantid){
        head['tenant-id'] = tenantid
      }
      return head;
    }
  },
  // mounted () {
    // this.loadDevicePartType()
  // },
  created () {
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model));
    this.loadAllDeviceType()
  },
  methods: {
    convertToTreeSelect (data) {
      return data.map(item => {
        const title = item.typeName || item.title || '未知标题';
        // 创建基本节点
        const node = {
          key: item.id,
          value: item.id,
          title: title
        };
        // 如果有子节点，递归处理
        if (item.subTypes && item.subTypes.length > 0) {
          node.children = this.convertToTreeSelect(item.subTypes);
        }
        return node;
      });
    },
    loadAllDeviceType() {
      getAction(this.url.listDeviceType).then((res) => {
        if (res.success) {
          this.deviceTypes = this.convertToTreeSelect(res.result)
        } else {
          this.$message.error(res.message)
        }
      })
    },
    loadDevicePartType() {
      getAction(this.url.listAllDeviceType, {pid:this.model.deviceTypeId,calss:2}).then((res) => {
        if (res.success) {
          this.devicePartTypes = this.convertToTreeSelect(res.result)
        } else {
          this.$message.error(res.message)
        }
      })
    },
    add (selectId) {
      // console.log('partId', partId)
      // this.modelDefault.departTypeId = partId
      // console.log('modelDefault', this.modelDefault)
      this.edit(this.modelDefault);
    },
    edit (record) {
      this.model = Object.assign({}, record);
      this.visible = true;
    },
    submitForm () {
      const that = this;
      // 触发表单验证
      this.$refs.form.validate(valid => {
        if (valid) {
          that.confirmLoading = true;
          let httpurl = '';
          let method = '';
          if(!this.model.id){
            httpurl+=this.url.add;
            method = 'post';
          }else{
            httpurl+=this.url.edit;
            method = 'put';
          }
          httpAction(httpurl,this.model,method).then((res)=>{
            if(res.success){
              that.$message.success(res.message);
              that.$emit('ok');
            }else{
              that.$message.warning(res.message);
            }
          }).finally(() => {
            that.confirmLoading = false;
          })
        }

      })
    },
    handleUpload(info, field) {
      if (info.file.status === "done") {
        this.model[field] = info.file.response.message
        this.$message.success("上传成功")
      } else if (info.file.status === "error") {
        this.$message.error("文件上传失败")
      }
    },
  }
}
</script>