<template>
  <div>
     <el-dialog
      :title="type === 'edit' ? '编辑流程' : '添加流程'"
      :visible.sync="dialogVisible"
      width="40%"
    >
      <el-form
        ref="editRef"
        label-width="125px"
        label-position="right"
        :model="form"
      >
        <el-form-item label="父流程名称" v-if="type !== 'new'">
          <span slot="label"><span style="color:red">* &nbsp;</span>父流程名称</span>
          <el-input v-model="form.parentname" :disabled="true"/>
        </el-form-item>
        <el-form-item label="父流程名称" v-else>
          <span slot="label"><span style="color:red">* &nbsp;</span>父流程名称</span>
          <el-input placeholder="请选择父流程名称" v-model="form.parentname" class="input-with-select" :disabled="true">
            <el-button slot="append" @click="selectProcess()">选择</el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="流程名称">
          <span slot="label"><span style="color:red">* &nbsp;</span>流程名称</span>
          <el-input v-model="form.name" clearable />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handlerAddConfirm">确 定</el-button>
      </span>
    </el-dialog>
    <pro-tree v-model="prodialogVisible" @confirm=proConfirm></pro-tree>
  </div>
</template>

<script>
import {
  getProcessTreesave,
  getProcessTreeupdate,
  getProcessTreeNodeCode
} from '../../../api/processTree'
import {
  processSaveAttr,
  queryProcessDesignListInfo
} from '../../../api/processDesignCenter'
import proTree from './proTree.vue'
  export default {
    name: 'addProcessDialog',
    components: {
      proTree
    },
    data() {
      return {
        form: {
          name: '',
          parentname: ''
        },
        dialogVisible: false,
        rules: {
          name: [{ required: true, message: " ", trigger: "blur" }],
          parentname: [{ required: true, message: " ", trigger: "blur" }]
        },
        prodialogVisible: false
      }
    },
    props: {
      value: {
        type: Boolean,
        default: false
      },
      processForm: {
        type: Object,
        default: () => {
          return {}
        }
      },
      type: {
        type: String,
        default: 'add'
      },
      saveType: {
        type: String,
        default: 'ico_save'
      },
      treeTempId: {
        type: String,
        default: ''
      }
    },
    computed: {
      userid() {
        return JSON.parse(localStorage.getItem("portalCurrentUserInfo") || "{}")
          .empuid;
      },
      username() {
        return JSON.parse(localStorage.getItem("portalCurrentUserInfo") || "{}")
          .cnname;
      },
    },
    watch: {
      value(val) {
        this.dialogVisible = val;
        if(val){
          console.log(this.type)
          this.form= this.processForm
        }
      },
      dialogVisible(val) {
        this.$emit("input", val);
      },
      type(val) {
        console.log(val, 'this.type')
      },
    },
    methods: {
      handlerAddConfirm() {
        console.log('handlerAddConfirm', this.type)
        if (!this.form.name) {
          this.$message({
            message: "请填写流程名称！",
            type: "warning"
          });
          return
        } else if (!this.form.parentname) {
          this.$message({
            message: "请选择父流程名称！",
            type: "warning"
          });
          return
        } else {
          this.savedate();
        }
        //this.$refs.editRef.validate(valid => {
          //if (valid) {
            //console.log('11111111')
            //this.savedate();
          //} else {
            //console.log('2222222')
          //}
        //})
      },
      savedate() {
        console.log('666666666', this.type)
        if (this.type === 'add' || this.type === 'selfBuilt') {
          if (this.type === 'selfBuilt') {
            let flag = window.isNodesInProcess(null, null, this.saveType)
            if (!flag) {
              return
            }
          }
            this.dialogVisible = false;
            // 正式用，先提交流程，流程结束后真正保存
            // getProcessTreesaveT(this.updatenewForm).then(res => {
            //   console.log(res)
            //   let url = "http://180.101.125.105:7011/bas/oAuth?"
            //   window.open(url)
            // })
            // 测试用，不走流程直接保存
            getProcessTreesave(this.form).then(res => {
              if (!res) return false;
              if (res) {
                this.$message({
                  type: "success",
                  message: res
                });
              }
              this.form = {
                name: '',
                typeid: '2',
                systematic: 'function',
                displaymode: 'treeShape'
              }
              this.$emit('confirm', '')
              // const node = this.$refs.tree.getNode(this.treeTempId); // 通过节点id找到对应树节点对象
              // node.loaded = false;
              // node.expand();
            })
        } else if (this.type === 'edit') {
          this.dialogVisible = false;
          // 正式用，先提交流程，流程结束后真正保存
          // getProcessTreeupdateT(this.updateForm).then(res => {
          //   console.log(res)
          //   let url = "http://180.101.125.105:7011/bas/oAuth?"
          //   window.open(url)
          // })
          // 测试用，不走流程直接保存
          getProcessTreeupdate(this.form).then(res => {
              if (!res) return false;
              if (res) {
                this.$message({
                  type: "success",
                  message: res
                });
              }
              this.form = {
                name: '',
                typeid: '2',
                systematic: 'function',
                displaymode: 'treeShape'
              }
              console.log('confirm')
              this.$emit('confirm', '')
              // const node = this.$refs.tree.getNode(this.treeTempId); // 通过节点id找到对应树节点对象
              // node.loaded = false;
              // node.expand();
            }).catch(err => {
              this.$message({
                type: "error",
                message: "框架名称重复!"
              });
            });
        } else if (this.type == 'new') {
          // 测试用，不走流程直接保存
          console.log(window.isNodesInProcess(null, null, this.saveType), 'new666')
          let flag = window.isNodesInProcess(null, null, this.saveType)
          if (flag) {
            this.dialogVisible = false;
            getProcessTreesave(this.form).then(resp => {
            if (!resp) return false;
            if (resp) {
              this.$message({
                type: "success",
                message: resp
              });
            }
            queryProcessDesignListInfo(this.form.pid, {
                    fullFilters: [
                      {
                        filters: [
                          {
                            key: "code",
                            opt: "LIKE",
                            type: "S",
                            value: '',
                            logic: "or",
                          },
                          {
                            key: "name",
                            opt: "LIKE",
                            type: "S",
                            value: '',
                            logic: "or",
                          },
                        ],
                        logic: "and",
                      },
                    ],
                    logic: "and",
                    pageNum: 1,
                    pageSize: 999,
                    sort: "desc"
                  // getProcesslist({
                  //   filters: [{ key: "modelid", value: self.modelid }],
                  //   orderby: "createon",
                  //   pageNum: 1,
                  //   pageSize: 10,
                  //   sort: "desc",
                  }).then((res) => {
                    if (!res) return false;
                    let item = res.list[res.list.length -1]
                    let obj = {
                      id: item.bpmid,
                      listid: item.id,
                      treeId: this.form.pid,
                      processName: item.name,
                      username: '',
                      processNum: item.code,
                      state: item.state,
                      version: item.version,
                      isRead: 'no',
                      item: item,
                      treeData: item
                    }
                    if (item.state === "2") { //  新增的都是2 可以不加这个判断
                      processSaveAttr({
                        // id: item.bpmid,
                        bpo: item.bpo,
                        bponame: item.bponame,
                        code: item.code,
                        listid: item.id,
                        modelid: item.id,
                        signer: this.userid,
                        signername: this.username,
                        version: item.version,
                        name: item.name,
                        modelInstitution: {},
                      }).then((rt) => {
                        if (!rt) return false;
                        obj.state = '5';
                        obj.item.state = '5';
                        obj.id = rt.split(",")[0]
                        sessionStorage.setItem('processTabMenu', JSON.stringify([obj]))
                        sessionStorage.setItem('processInfo', JSON.stringify(obj))
                        window.onBtnSaveClick(null, null, this.saveType, obj.id)
                      });
                    } else {
                      sessionStorage.setItem('processTabMenu', JSON.stringify([obj]))
                      sessionStorage.setItem('processInfo', JSON.stringify(obj))
                      window.onBtnSaveClick(null, null, this.saveType, obj.id)
                    }
                  });
          })
          }
        }
      },
      selectProcess () {
        this.prodialogVisible = true
      },
      proConfirm (data) {
        this.type = 'new'
        console.log(data, this.type, 'proConfirm')
        this.form.pid = data.id;
        this.form.status = data.state;
        this.form.parentname = data.name;
        this.form.rank = data.rank + 1;
        getProcessTreeNodeCode(data.id).then(res => {
          if (!res) return
          this.form.name = "";
          this.form.ename = "";
          this.form.code = res.code;
          this.form.rank = data.rank + 1;
          if (res.code.substr(2, 1) || res.code.substr(3, 1) == 0) {
            this.form.rank = 2;
          }
          if (data.id == "79957553BD2F3978E053BF1A13ACD486") {
            this.form.businessLayer = true;
            this.form.code = "";
          } else {
            this.form.businessLayer = false;
          }
        });
      }
    }
  }
</script>

<style lang='scss' scoped>
/deep/.el-input-group__append {
  background-color: #2d42af;
  border-color: #2d42af;
  color: #fff
}
</style>
