<template>
  <view class="content">
    <view class="title"> 新增项目 </view>
    <uni-forms
      :modelValue="formData"
      label-position="left"
      class="form"
      ref="form"
      :rules="rules"
    >
      <uni-forms-item required label="项目名称" name="project_name">
        <uni-easyinput
          type="text"
          v-model="formData.project_name"
          class="input"
        />
      </uni-forms-item>
      <uni-forms-item label="项目类别" name="type" required>
        <picker
          @change="selectChangeType"
          :range="typeList"
          :range-key="'name'"
          :value="
            formData.type &&
            typeList.findIndex((item) => item.id == formData.type.id)
          "
        >
          <view class="select">
            {{
              formData.type && `${formData.type.name}(${formData.type.code})`
            }}
          </view>
        </picker>
      </uni-forms-item>
      <uni-forms-item label="流程" name="flow">
        <picker disabled>
          <view class="select">
            {{
              formData.type && (formData.type.id == 7 ? "研发立项" : "销售立项")
            }}
          </view>
        </picker>
      </uni-forms-item>
    </uni-forms>
    <uni-forms
      :modelValue="formData"
      label-position="left"
      class="form"
      ref="fullForm"
      :rules="rules"
      v-show="!formData.type || (formData.type && formData.type.id != 7)"
    >
      <uni-forms-item label="行业名称" name="industry" required>
        <picker
          @change="selectChangeIndustry"
          :range="industryList"
          :range-key="'name'"
          :value="
            formData.industry &&
            typeList.findIndex((item) => item.id == formData.industry.id)
          "
        >
          <view class="select">
            {{
              formData.industry &&
              `${formData.industry.name}(${formData.industry.code})`
            }}
          </view>
        </picker>
      </uni-forms-item>
      <uni-forms-item label="项目地区" name="location" required>
        <picker
          mode="multiSelector"
          @columnchange="bindChangeLocationColumn"
          @change="selectChangeLocation"
          :range="locationList"
          :range-key="'name'"
          :value="locationIndex"
        >
          <view class="select">
            {{
              formData.location &&
              `${formData.location.name}(${formData.code.location})`
            }}
          </view>
        </picker>
      </uni-forms-item>
      <uni-forms-item label="项目简称" name="name" required>
        <uni-easyinput
          type="text"
          v-model="formData.name"
          class="input"
          :clearable="false"
          @blur="onChangeName"
        />
      </uni-forms-item>
      <uni-forms-item label="项目期数" name="version" required>
        <picker
          @change="selectChangeVersion"
          :range="versionList"
          :value="formData.version && formData.version - 1"
        >
          <view class="select">
            {{ versionList[this.formData.version - 1] }}
          </view>
        </picker>
      </uni-forms-item>
      <uni-forms-item label="项目编号" name="code">
        <view>
          {{
            `${formData.code.type}-${formData.code.industry}-${formData.code.location}-${formData.code.name}-${formData.code.version}`
          }}
        </view>
      </uni-forms-item>
    </uni-forms>
    <view class="group">
      <button @click="onHandleSubmit(0)" class="commit">取消</button>
      <button @click="onHandleSubmit(1)" type="primary" class="commit">
        确定
      </button>
    </view>
  </view>
</template>

<script>
import {
  queryProjectType,
  queryIndustry,
  queryFlow,
  createApproval,
  updateApproval,
} from "@/services/project";
import provinces from "./provinces";
import { mapState } from "vuex";
const versionList = ["一期", "二期", "三期", "四期", "五期"];
export default {
  data() {
    return {
      formData: {
        project_name: null,
        type: null,
        flow: null,
        industry: null,
        location: null,
        name: null,
        version: null,
        code: {
          type: "***",
          industry: "***",
          location: "***",
          name: "***",
          version: "*",
        },
      },
      rules: {
        project_name: {
          rules: [
            {
              required: true,
              errorMessage: "请输入项目名称",
            },
          ],
        },
        type: {
          rules: [
            {
              required: true,
              errorMessage: "请选择项目类别",
            },
          ],
        },
      },
      fullRules: {
        industry: {
          rules: [
            {
              required: true,
              errorMessage: "请选择行业名称",
            },
          ],
        },
        location: {
          rules: [
            {
              required: true,
              errorMessage: "请选择地区",
            },
          ],
        },
        name: {
          rules: [
            {
              required: true,
              errorMessage: "请输入项目简称",
            },
            {
              maxLength: 3,
              errorMessage: "项目简称不能超过3位",
            },
            {
              validateFunction: function (rule, value, data, callback) {
                if (value.match(/[^A-Za-z]/g)) {
                  callback("项目简称只能是英文字符");
                } else {
                  callback();
                }
              },
            },
          ],
        },
        version: {
          rules: [
            {
              required: true,
              errorMessage: "请选择期数",
            },
          ],
        },
      },
      project_id: 0,
      typeList: [],
      industryList: [],
      flowList: [],
      versionList,
      provinces,
      locationList: [provinces, []],
      locationIndex: [0, 0],
    };
  },
  computed: {
    ...mapState(["currentProject"]),
  },
  onLoad(options) {
    if (options.project_id) {
      this.project_id = options.project_id;
    }
    this.init(options);
  },
  onReady() {
    this.$refs.fullForm.setRules(this.fullRules);
  },
  methods: {
    async submitHelper(full) {
      let payload = {
        project_name: this.formData.project_name,
        type_id: Number(this.formData.type.id),
        flow_id: Number(this.formData.flow.id),
        node_id: this.flowList.find((item) => item.id == this.formData.flow.id)
          .Nodes[0].id,
      };
      if (full) {
        payload = {
          ...payload,
          industry_id: Number(this.formData.industry.id),
          location: this.formData.location.name,
          location_code: this.formData.location.code,
          name: this.formData.name,
          version: this.formData.version + "",
          project_full_code:
            this.formData.code.type +
            this.formData.code.industry +
            this.formData.code.location +
            this.formData.code.name +
            this.formData.code.version,
        };
      }
      if (this.project_id == 0) {
        await createApproval(payload);
      } else {
        payload.id = Number(this.project_id);
        await updateApproval(payload);
      }
      uni.navigateTo({
        url: "./list",
      });
    },
    onHandleSubmit(value) {
      if (value) {
        this.$refs.form.validate((err) => {
          if (!this.formData.type || this.formData.type.id != 7) {
            this.$refs.fullForm.validate((errFull) => {
              if (!err && !errFull) {
                this.submitHelper(1);
              }
            });
          } else {
            if (!err) {
              this.submitHelper(0);
            }
          }
        });
      } else {
        uni.navigateTo({
          url: "./list",
        });
      }
    },
    async init(options) {
      let res;
      res = await queryProjectType();
      this.typeList = res.data;
      res = await queryIndustry();
      this.industryList = res.data;
      res = await queryFlow();
      this.flowList = res.data;
      let form = this.formData;
      let code = this.formData.code;
      let current = this.currentProject;
      if (options.project_id) {
        form.project_name = current.project_name;
        form.type = this.typeList.find(
          (item) => item.id == this.currentProject.type_id
        );
        form.flow = this.flowList.find(
          (item) => item.id == this.currentProject.flow_id
        );
        if (current.type_id != 7) {
          form.industry = this.industryList.find(
            (item) => item.id == this.currentProject.industry_id
          );
          form.location = {
            name: current.location,
            code: current.location_code,
          };
          form.name = current.name;
          form.version = current.version;
          code.type = form.type.code;
          code.industry = form.industry.code;
          code.location = form.location.code;
          code.name = form.name;
          code.version = form.version;

          const searchLocation = (list, name) => {
            for (let i = 0; i < list.length; ++i) {
              if (list[i].children) {
                let childrenIndex = searchLocation(list[i].children, name);
                if (childrenIndex[0] != -1) return [i, childrenIndex[0]];
              } else {
                if (list[i].name == name) return [i, 0];
              }
            }
            return [-1, -1];
          };

          this.locationIndex = searchLocation(this.provinces, current.location);
          if (this.provinces[this.locationIndex[0]].children)
            this.locationList[1] =
              this.provinces[this.locationIndex[0]].children;
        }
      }
    },
    binddata(name, value) {
      this.$refs.fullForm.setValue(name, value);
    },
    selectChangeType(e) {
      let form = this.formData;
      let code = this.formData.code;
      form.type = this.typeList[e.target.value];
      code.type = form.type.code;
      this.$refs.form.setValue("type", e.target.value);
      if (form.type.id == 7) {
        form.flow = this.flowList.find((item) => item.id == 4);
        form.industry = null;
        form.location = null;
        form.name = null;
        form.version = null;
        code.industry = "***";
        code.location = "***";
        code.name = "***";
        code.version = "*";
      } else form.flow = this.flowList.find((item) => item.id == 1);
    },
    selectChangeIndustry(e) {
      this.formData.industry = this.industryList[e.target.value];
      this.formData.code.industry = this.formData.industry.code;
      this.binddata("industry", e.target.value);
    },
    onChangeName(e) {
      let name = e.detail.value.toUpperCase();
      while (name.length < 3) name += "V";
      this.formData.name = name;
      this.formData.code.name = name;
    },
    selectChangeVersion(e) {
      this.formData.version = e.target.value + 1;
      this.formData.code.version = this.formData.version + "";
      this.binddata("version", e.target.value);
    },
    bindChangeLocationColumn(e) {
      if (e.target.column == 0) {
        this.locationList[1] = this.provinces[e.target.value].children || [];
        this.locationIndex = [e.target.value, 0];
      }
    },
    selectChangeLocation(e) {
      let multiIndex = e.target.value;
      this.locationIndex = multiIndex;
      // let location = this.formData.location;
      // let locationCode = this.formData.code.location;
      let location = this.provinces[multiIndex[0]].children
        ? this.provinces[multiIndex[0]].children[multiIndex[1]]
        : this.provinces[multiIndex[0]];
      location.code =
        location.code.length == 4 ? location.code.substr(1) : location.code;
      this.formData.location = location;
      this.formData.code.location = location.code;
      this.binddata("location", e.target.value);
    },
  },
};
</script>

<style lang="less" scoped>
.content {
  display: flex;
  flex-wrap: wrap;
}
.title {
  width: 100%;
  padding: 0 20px 20px 20px;
  background: #f8f8f8;
  font: 24px bold;
}
.form {
  margin: 20px 10% 0 10%;
  width: 100%;
}
.input {
  border: 1px solid #666;
}
.select {
  width: 100%;
  height: 72rpx;
  line-height: 70rpx;
  border: 1px solid #666;
  padding-left: 20rpx;
}
.group {
  width: 100%;
  display: flex;
  position: fixed;
  flex-wrap: wrap;
  justify-content: flex-start;
  bottom: 0;
  left: 0;
  .commit {
    width: 50%;
    border-radius: 0;
    margin: inherit;
  }
}
</style>
