<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="modelType">
              <j-dict-select-tag v-model="model.modelType" dictCode="work_order" placeholder="请选择工单类型" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="工单模板" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="modelUrl">
              <a-upload name="file" :multiple="false" :headers="tokenHeader" :action="uploadWorkModelUrl" @change="handleUpload">
                <a-button icon="cloud-upload">上传模板文件</a-button>
              </a-upload>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="修程/故障类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="regularId">
              <a-tree-select
                v-model="model.regularId"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                :tree-data="treeData"
                placeholder="请选择修程/故障类型"
                tree-default-expand-all
              >
              </a-tree-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="是否委外" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isOutsource">
              <a-select v-model="model.isOutsource" :options="selectOptions" placeholder="是否委外" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="ramark">
              <a-input v-model="model.ramark" placeholder="请输入备注"  ></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>

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

  export default {
    name: 'WorkOrderModelForm',
    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: {
           modelType: [
              { required: true, message: '请输入工单类型!'},
           ],
           modelUrl: [
             { required: true, validator: this.validateUrl, trigger: 'blur' }
           ],
           regularId: [
              { required: true, message: '请输入修程/故障类型!'},
           ],
        },
        url: {
          add: "/workOrder/workOrderModel/add",
          edit: "/workOrder/workOrderModel/edit",
          queryById: "/workOrder/workOrderModel/queryById",
          uploadWorkModel: "sys/upload/uploadMinioNew"
        },
        treeData: [],
        selectOptions: [
          {
            label: '是',
            value: 1,
          },
          {
            label: '否',
            value: 0,
          },
        ]
      }
    },
    computed: {
      validateUrl(rule, value, callback) {
        if (!value) {
          callback(new Error('请上传工单模板！'));
        } else {
          callback();
        }
      },
      formDisabled(){
        return this.disabled
      },
      uploadWorkModelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.uploadWorkModel}`;
      },
      //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;
      }
    },
    created () {
       //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
      this.queryMap();
    },
    methods: {
      add () {
        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) {
        if (info.file.status === "done") {
          // 上传成功
          this.model.modelUrl = info.file.response.message; // 获取后端返回的文件 URL
          this.$refs.form.clearValidate('modelUrl')
          // this.updateRecord(fileUrl)
        } else if (info.file.status === "error") {
          // 上传失败
          this.$message.error("文件上传失败");
        }
      },
      queryMap() {
        getAction("/regular/regular/querymap" ).then((res) => {
          if (res.success) {
            this.treeData = res.result;
          }
        })
      },
    }
  }
</script>